Opposite PHP function of strstr to return first part of string, not last
Asked Answered
W

3

5

I have an string, something like this:

$abcdef(+$1.00)

I'm trying to get the first part of the string before the first parenthesis:

$abcdef

Currently if I use strstr() it will return the part of the string after the specified character:

$newstr = strstr($var, '(');

I want the part before the occurrence. What is the reverse or opposite function of strstr() that will do that?

Woadwaxen answered 22/5, 2012 at 17:35 Comment(0)
M
11

Pass true as the third parameter.

From the manual page you have linked:

string strstr (string $haystack , mixed $needle [, bool $before_needle = false ])

before_needle: If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

Note: This parameter was only added in PHP 5.3. If for some reason you are left with an older version, a combination of substr() and strpos() should help:

$newstr = substr( $var, 0, strpos( $var, '(' ) );
Muenster answered 22/5, 2012 at 17:37 Comment(1)
Is that all I had to do?!? Thanks @bažmegakapaWoadwaxen
U
4

Set third parameter of strstr to true it will return occurrence before needle

Urita answered 22/5, 2012 at 17:38 Comment(0)
M
0

Better method to do this in a simple way is:

$newstr = explode('(',$var)[0];

Explanation: $result = explode('search_for_this' , $search_in_this)[0];

Monolingual answered 20/10, 2014 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.