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

53,674

Solution 1

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.

Solution 2

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);
Share:
53,674
Marco Demaio
Author by

Marco Demaio

Just love coding all day long! Now I'm using PHP and Javascript for my daytime job. I took part in realizing all the back end application to handle the orders, contracts and invoices for a site that sells posta certificata per aziende. Language I love most is C++ Language I hate most is VB6/VB.NET Wishes: to see PHP becoming more OO with operator overloading, and Python add curly braces. I have started coding in BASIC since I was a 13 years old kid with a Commodore 64 and Apple II. During University they taught me C and C++ and JAVA and I realized even more how much I love to code. :) Funny stuff: Micro Roundcube plugin to improve the search box

Updated on July 18, 2022

Comments

  • Marco Demaio
    Marco Demaio almost 2 years

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

    Because 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 cut off.

    Thanks,