Remove chunk from a string

Asked

Viewed 590 times

4

have a string, example:

32137hyb8bhbhu837218nhbuhuh&3298j19j2n39

I want to remove (clear) from the string everything that comes after the &.

Please, how to do this?

  • https://secure.php.net/manual/en/function.strstr.php

5 answers

5


You can use the function explode to do this.

$str = "32137hyb8bhbhu837218nhbuhuh&3298j19j2n39";
$str = explode("&",$str);
echo $str[0];

That’s the way out

32137hyb8bhbhu837218nhbuhuh

Explanation

The function explode divides a string by the given separator and returns an array containing the separate parts. Since it splits the string 32137hyb8bhbhu837218nhbuhuh&3298j19j2n39 in two parts 32137hyb8bhbhu837218nhbuhuh and 3298j19j2n39 and stores each part in an array index. The part you need can be accessed in the first array index, in this case, $str[0].

You can see working online here

5

Can use function strstr() passing the third argument that returns only the left part of the delimiter:

echo strstr('32137hyb8bhbhu837218nhbuhuh&3298j19j2n39', '&', true);

Returns:

32137hyb8bhbhu837218nhbuhuh

4

Try this:

$retorno = explode("&","32137hyb8bhbhu837218nhbuhuh&3298j19j2n39")[0];

See Example here

4

If you have any preference for REGEX, what I find difficult, could use this:

$string = '32137hyb8bhbhu837218nhbuhuh&3298j19j2n39';

preg_match('/(.*)&/', $string, $match);

echo $match[1];

Answer:

32137hyb8bhbhu837218nhbuhuh

The preg_match uses the REGEX of /(.*)&/ will get everything (.*) earlier than &.

Remembering that it is just another alternative method to the methods that have already been answered.

4

Adding one more option, you can use in a single sequence the combination of functions substr and strrpos:

$text = '32137hyb8bhbhu837218nhbuhuh&3298j19j2n39';
echo substr($text, 0, strrpos($text, '&'));

Resulting in:

32137hyb8bhbhu837218nhbuhuh

Check out on ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.