2

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?

4 Answers 4

5

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, '/'));
Sign up to request clarification or add additional context in comments.

4 Comments

If there is no /, strpos will return false and substr will return an empty string.
+1 for simplicity. preg is a waste, as is exploding into an array.
@Gumbo - I was just thinking that... updating
thank you, and thanks to all for the alternatives, they help me to understant what i can do
3

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";

Comments

2

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.

3 Comments

Any suggestions how to remove from the last / to the end?
@geotheory Try /[^/]*$.
Tx. Figured out a non-regex solution too: str.split("/").slice(0, str.split("/").length-1).join('/').concat("/")
2

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);
}

1 Comment

Sorry, I forgot the delimiters too... :S fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.