Vidya Venkat
Vidya Venkat

Reputation: 3

Get text between two substrings

How can I extract https://example.com/gamer?hid=.115f12756a8641 from the below string ,i.e from url

rrth:'http://www.google.co',cctp:'323',url:'https://example.com/gamer?hid=.115f12756a8641',rrth:'https://another.com'

Upvotes: 0

Views: 69

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76405

Simple regex:

preg_match('/url\s*\:\s*\'([^\']+)/i',$theString,$match);
echo $match[1];//should be the url

How it works:

/url\s*\:\s*: matches url + [any number of spaces] + : (colon)+ [any number of spaces]
But we don't need this, that's where the second part comes in
\'([^\']+)/i: matches ', then the brackets (()) create a group, that will be stored separately in the $matches array. What will be matches is [^']+: Any character, except for the apostrophe (the [] create a character class, the ^ means: exclude these chars). So this class will match any character up to the point where it reaches the closing/delimiting apostrophe.
/i: in case the string might contain URL:'http://www.foo.bar', I've added that i, which is the case-insensitive flag.

That's about it.
Perhaps you could sniff around here to get a better understanding of regex's

note: I've had to escape the single quotes, because the pattern string uses single quotes as delimiters: "/url\s*\:\s*'([^']+)/i" works just as well. If you don't know weather or not you'll be dealing with single or double quotes, you could replace the quotes with another char class:

preg_match('/url\s*\:\s*[\'"]([^\'"]+)/i',$string,$match);

Obviously, in that scenario, you'll have to escape the delimiters you've used for the pattern string...

Upvotes: 0

Martin Ender
Martin Ender

Reputation: 44259

If your input string is called $str:

preg_match('/url:\'(.*?)\'/', $str, $matches);
$url = $matches[1];

(.*?) captures everything between url:' and ' and can later be retrieved with $matches[1].

The ? is particularly important. It makes the repetition ungreedy, otherwise it would consume everything until the very last '.

If your actual input string contains multiple url:'...' section, use preg_match_all instead. $matches[1] will then be an array of all required values.

Upvotes: 4

Related Questions