3

I have a string like that as json response for a script:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, HTTP://unknown/string/in/unknown/place/ , sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"

is there a way to replace with an empty string using regular expression and php preg_replace?

I'm not familiar with regular expression, could you just provide an example? I basically need to remove the substring starting with 'http' and finishing with a space, IF possible.

thanks

1 Answer 1

5

Something like

preg_replace("/HTTP\S+\s,/", "","Lorem ipsum dolor sit amet, consectetur adipiscing elit, HTTP://unknown/string/in/unknown/place/ , sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" );

Will give output as

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

Regex /HTTP\S+\s,/

  • \S matches anything other than a space

  • \s matches a space

Regex Demo

EDIT

A better solution like

/HTTP\S+(\s,|$)/

So that the link can apear anywhere in the string even at the end.

Example

preg_replace("/HTTP\S+(\s,|$)/", "","Lorem ipsum dolor sit amet, consectetur adipiscing elit, HTTP://unknown/string/in/unknown/place/" );
=> Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Regex Demo

Sign up to request clarification or add additional context in comments.

3 Comments

just another thing: if my unknown url is in the end of the main string without space and slash in the end, there is a way to match it? If not I would use string split, but if there is a way it would be better so that I can match all possibilities in one function call: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, t.co/LjAezrssLM" if this is not possibile just thanks again!
@btb84 I have edited my answer a bit. It would match the link anywhere . Hope it helps you:)
great, now it matches the string correctly everywhere, and now my feed parser works fine! big big thank my friend!

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.