日曜プログラミング

PHP好き集まれ〜!!

strpos()とsubstr()

メモ書きということで、

xxxxx?yyyyyから?より前の文字列を抽出するTipsを書きます。

?より前の文字列を抽出するためにはstrpos()とsubstr()を使います。
ちなみにこの例に限ってはstrrpos()を使っても出来ます。

<?php
$str = "xxxxx?yyyyy";

//?より前の文字列を抽出する
if(false !== ($count = strpos($str, '?'))){
	$before = substr($str, 0, $count);
}
echo $before, PHP_EOL; // xxxxx

strpos()の返り値を上手く利用してる。