Thursday, April 21, 2011

php preg_match two examples

Hello, I need to preg_match for

src="http://      "

where the blank space following // is the rest of the url ending with the ". My adapted doesn't seem to work:

preg_match('#src="(http://[^"]+)#', $data, $match);

And I am also struggling to get text that starts with > and ends with EITHER a full stop . or an exclamation mark ! or a question mark ? I have no idea how to do this one. An example of the text I want to preg_match for is:

 blahblahblah>Hello world this is what I want.

I'm hoping a kind preg_match guru can tell me the answer and save me hours of headscratching.

Thanks for reading.

From stackoverflow
  • As for the URL:

    preg_match('#src="(.*?)"#', $data, $match);
    

    and for the second case, use />(.*?)(\.|!|\?)/

    daemonfire300 : Good solution, but XPath would solve this WITHOUT ANY preg_match ;)
    Dan Wilbur : Thanks Igor. I added a # into the first one to make it work and the second works great too. Thanks very much.
    igor : Thanks Dan. I corrected that typo in my answer.
  • (.*?)" will match any character greedily up until the time it sees the end double quote

    Tordek : Lazily, you mean.
  • It seems that you want to parse a document or string which follows a HTML, DOM, XML or something similiar structure. Use XPath, and parse to the Tag and let it return the src Attribute, this will save much trouble and you can forget about regular expressions.

    Example: CLICK ME

0 comments:

Post a Comment