views:

57

answers:

4

I'm trying to remove from a string everything start with / char, so if I have

my_value/j/im<b*+èo[/h>e\ylo

I'd like to remove the string /j/im<b*+èo[/h>e\ylo and return only my_value. I thought to use something with str_replace but I'm not a great regex programmer and I'm doing practise with php.

function clean_value ($value) {
    return preg_replace ("^(/.*?)$", "", $value);
}

How can I do?

+2  A: 

You forgot the delimiters in your regular expression. And ^/ requires the string to start with a /.

Try this instead:

preg_replace("~/.*~", "", $value)

This will remove anything from the first / up to the end.

Gumbo
+2  A: 

You need to remove the starting caret from your regexp, and you can use a greedy match to get the rest of the string:

function clean_value ($value) {
    return preg_replace ("/\/.*/", "", $value);
}
Mike Houston
Sorry, I forgot the delimiters too... :S fixed.
Mike Houston
+3  A: 

The simplest things can be done without regex

$string = "my_value/j/im<b*+èo[/h>e\ylo";
$splitted = explode("/",$string,2);
echo  "$splitted[0]\n";
ghostdog74
+3  A: 

There is no reason to use regex here. Use a combo of strpos() and substr() instead:

$original = 'my_value/j/im<b*+èo[/h>e\ylo';

$removed = substr($original, 0, strpos($original, '/'));

The above will work if you can guarantee that the string will always have at least 1 / character in it. If you can't guarantee that or don't know, simply modify to:

$removed = (strpos($original, '/') === false)
             ? $original 
             : substr($original, 0, strpos($original, '/'));
John Rasch
If there is no `/`, `strpos` will return *false* and `substr` will return an empty string.
Gumbo
+1 for simplicity. preg is a waste, as is exploding into an array.
hobodave
@Gumbo - I was just thinking that... updating
John Rasch
thank you, and thanks to all for the alternatives, they help me to understant what i can do
Vittorio Vittori