PHP substr after a certain char, a substr + strpos elegant solution?
Your first approach is fine: Check whether x
is contained with strpos
and if so get anything after it with substr
.
But you could also use strstr
:
strstr($str, 'x')
But as this returns the substring beginning with x
, use substr
to get the part after x
:
if (($tmp = strstr($str, 'x')) !== false) { $str = substr($tmp, 1);}
But this is far more complicated. So use your strpos
approach instead.
Regexes would make it a lot more elegant:
// helo babeecho preg_replace('~.*?x~', '', $str);// Tuex helo babeecho preg_replace('~.*?y~', '', $str);
But you can always try this:
// helo babeecho str_replace(substr($str, 0, strpos($str, 'x')) . 'x', '', $str);// Tuex helo babeecho str_replace(substr($str, 0, strpos($str, 'y')) . 'y', '', $str);