Ryusuke Fuda's Tech Blog

Softweare Enginier about Web, iOS, Android.

正規表現でヒットした文字列を抽出, 後方参照(PHP)

■ preg_replace の後方参照を使う

$text = 'src="http://abcdefghtijklmn"';
$val = preg_replace('/src="(.*)"/', '${1}', $text);
var_dump($val); // http://abcdefghtijklmn が取得できる

正規表現の()の中にヒットした一個目が$valに入る。
${1}が一つ目のヒット、${2}で二個目にヒットしたもの。

参考)
http://web-dou.com/php/func/preg_replace.html
http://www.ipentec.com/document/document.aspx?page=php-regular-expression-search-and-get-str-preg_match