tags:

views:

37

answers:

3

Hello,

let's say I want to return all chars after some needle char 'x' from:

$source_str = "Tuex helo babe".

Normally I would do this:

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

Do you know a better/smarter (more elegant way) to do this?

Without using regexp that would not make it more elegant and probably also slower.

Unfortunately we can not do:

$source_str = substr(source_str, strpos(source_str, 'x') + 1);

Becaue when 'x' is not found strpos returns FALSE (and not -1 like in JS). FALSE would evaluate to zero, and 1st char would be always cutted off.

Thanks,

A: 

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.

Gumbo
But strstr return FALSE if needle is not found, not the entire string.
Marco Demajo
A: 
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);
dev-null-dweller
this will include the 'x' within $source_str though
adam
Well thanks for your answer, but it's argueable that this is more elegant, and definitely slower "If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead." [source: http://it.php.net/strstr]
Marco Demajo
I'm confused. `strpos` is to check for substring occurence and it is used in my answer. `strstr` is to return portion of string, only if substring occurs. I find it more elegant because it does'nt need auxiliary variable, there is no misleading assignment in `if()` line and it's shorter. The only flaw of it is what @adam mentioned
dev-null-dweller
@dev-null-dweller: sorry, I probably did not properly explain myself, I think using a strpos+strstr is slower than using a strpos+substr. I did not test for performance (so I'm not sure, but the speed difference might be unnoticable), but beside this, it's still a two line of codes with an if (very similar to code in my question), I was hoping someone could come out with a more concise solution.
Marco Demajo
A: 

Regexes would make it a lot more elegant:

// helo babe
echo preg_replace('~.*?x~', '', $str);

// Tuex helo babe
echo preg_replace('~.*?y~', '', $str);

But you can always try this:

// helo babe
echo str_replace(substr($str, 0, strpos($str, 'x')) . 'x', '', $str);

// Tuex helo babe
echo str_replace(substr($str, 0, strpos($str, 'y')) . 'y', '', $str);
Alix Axel