Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

substr

strpos

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,

like image 555
Marco Demaio Avatar asked Oct 27 '10 17:10

Marco Demaio


People also ask

How do I get the string after a specific character in PHP?

$data = "123_String"; $whatIWant = substr($data, strpos($data, "_") + 1); echo $whatIWant; Php Get String After Character.

What is the use of strpos () function in PHP?

The strpos() function finds the position of the first occurrence of a string inside another string.

How do you get something before a certain character?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.

What is substr () in PHP and how it is used?

substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above. Let us see how we can use substr() to cut a portion of the string.


2 Answers

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.

like image 157
Gumbo Avatar answered Oct 19 '22 10:10

Gumbo


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);
like image 37
Alix Axel Avatar answered Oct 19 '22 09:10

Alix Axel