以下URLからKWxxxの箇所を抽出したいです。
正規表現でどのようにするかご教授お願いいたします。
http://google.com/KWxxx
http://google.com/KWxxx/test
http://google.com/KWxxx?name=test
http://google.com?keyword=KWxxx
http://google.com?keyword=KWxxx&name=test
条件としてはKWという文字列は固定で入っており、それに続くxxxは英数字の文字列とします(文字数は不明)。
抽出例)
http://google.com/KWabcd1234 = KWabcd1234
http://google.com/KW1a2b3c4d = KW1a2b3c4d
$str1 = "http://google.com/KWxxx"; $str2 = "http://google.com/KWxxx/test"; $str3 = "http://google.com/KWxxx?name=test"; $str4 = "http://google.com?keyword=KWxxx"; $str5 = "http://google.com?keyword=KWxxx&name=test"; // 1 preg_match('/KW(.*)$/', $str1, $match); // 2 /が最後に入ってしまう preg_match('/KW(.*)//', $str2, $match); // 3 ?が最後に入ってしまう preg_match('/KW(.*)?/', $str3, $match); // 4 1と同じ // 5 #preg_match('/KW([^&\s]*)/', $str5, $match); var_dump($match);
これら1〜5のすべてを同一の正規表現で抽出したいのですが、可能でしょうか?