PHP substr after a certain char, a substr + strpos elegant solution? PHP substr after a certain char, a substr + strpos elegant solution? php php

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);


if(strpos($source_str, 'x') !== FALSE )   $source_str = strstr($source_str, 'x');

Less elegant, but without x in the beginning:

if(strpos($source_str, 'x') !== FALSE )   $source_str = substr(strstr($source_str, 'x'),1);