Search code examples
phpregexpreg-match

Regex trouble, capture until find space or endline


I'm trying to capture the following match:

"url: https://www.anysite/anything"

But sometime the string comes:

"url: https://www.anysite/anything another word"

But i just only want to match

"url: https://www.anysite/anything"

whether or not the "another word" comes.

So, my logic is capture until find the first space after the url address, or end of string. My REGEX IN PHP is:

preg_match("/(Url|url)(\:|\b)(\s\b|\b).+(\s|$)/",$linestring,$url_string);

But it always bring the "another word" too, instead of bring only until space.


Solution

  • The . is greedy unless the quantifier is made ungreedy with a ? or the U modified.

    (Url|url)(\:|\b)(\s\b|\b).+?(\s|$)
    

    Your actually can simplify it a bit further:

    [Uu]rl(?::|\b)\s?\b.+?(?:\s|$)
    

    If you want the URL bit capture the .+? with ().

    [Uu]rl(?::|\b)\s?\b(.+?)(?:\s|$)
    

    https://regex101.com/r/urq2fM/2/