How to Find Next String After the Needle Using Str

2019-02-25 06:06发布

问题:

I'm using PHP strpos() to find a needle in a paragraph of text. I'm struggling with how to find the next word after the needle is found.

For example, consider the following paragraph.

$description = "Hello, this is a test paragraph.  The SCREENSHOT mysite.com/screenshot.jpg and the LINK mysite.com/link.html is what I want to return.";

I can use strpos($description, "SCREENSHOT") to detect if SCREENSHOT exists, but I want to get the link after SCREENSHOT, namely mysite.com/screenshot.jpg. In a similar fashion, I want to detect if the description contains LINK and then return mysite.com/link.html.

How can I use strpos() and then return the following word? I'm assuming this might be done with a RegEx, but I'm not sure. The next word would be "a space after the needle, followed by anything, followed by a space".

Thanks!

回答1:

Or the "old" way... :-)

$word = "SCREENSHOT ";
$pos = strpos($description, $word);
if($pos!==false){
    $link = substr($description, $pos+strlen($word));
    $link = substr($link, strpos($link, " "));
}


回答2:

You could do this with a single regular expression:

if (preg_match_all('/(SCREENSHOT|LINK) (\S+?)/', $description, $matches)) {
    $needles = $matches[1]; // The words SCREENSHOT and LINK, if you need them
    $links = $matches[2]; // Contains the screenshot and/or link URLs
}


回答3:

I did a little testing on my site using the following:

$description = "Hello, this is a test paragraph. The SCREENSHOT mysite.com/screenshot.jpg and the LINK mysite.com/link.html is what I want to return.";

$matches = array();
preg_match('/(?<=SCREENSHOT\s)[^\s]*/', $description, $matches);
var_dump($matches);
echo '<br />';
preg_match('/(?<=LINK\s)[^\s]*/', $description, $matches);
var_dump($matches);

I'm using positive lookbehind to get what you want.



标签: php strpos