Remove with regex the end portion of a string
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 clea开发者_如何转开发n_value ($value) {
return preg_replace ("^(/.*?)$", "", $value);
}
How can I do?
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, '/'));
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";
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.
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);
}
精彩评论