Remove part of a string

4

I have a string, example:

32137hyb8bhbhu837218nhbuhuh&3298j19j2n39

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

Please, how to do this?

    
asked by anonymous 26.01.2017 / 05:23

5 answers

5

You can use the explode function to do this.

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

What is the way out

32137hyb8bhbhu837218nhbuhuh

Explanation

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

You can see it working online here

    
26.01.2017 / 05:38
5

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

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

Return:

32137hyb8bhbhu837218nhbuhuh
    
26.01.2017 / 13:39
4

Try this:

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

See Example here

    
26.01.2017 / 05:48
4

If you have a preference for REGEX , which I find difficult, you could use this:

$string = '32137hyb8bhbhu837218nhbuhuh&3298j19j2n39';

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

echo $match[1];

Answer:

32137hyb8bhbhu837218nhbuhuh

preg_match uses REGEX of /(.*)&/ will get everything ( .* ) that is before & .

    

26.01.2017 / 10:34
4

By adding one more option, you can use the combination of % w / a> and substr :

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

Resulting in:

32137hyb8bhbhu837218nhbuhuh

Check out ideone

    
26.01.2017 / 13:27