How to find the next line after the needle using Strpos ()

I use PHP strpos()to find the needle in a paragraph of text. I struggle with finding 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 determine if SCREENSHOT exists, but I want to get the link after SCREENSHOT, namely mysite.com/screenshot.jpg. Similarly, I want to determine if the description contains LINK, and then returns mysite.com/link.html.

How can I use strpos()and then return the next word? I guess this can be done with RegEx, but I'm not sure. The next word will be “space after the needle, followed by something, and then space”.

Thank!

+3
source share
3

"" ...: -)

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

:

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
}
+1

, :

$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 use a positive lookbehind to get what you want.

0
source

Source: https://habr.com/ru/post/1789326/


All Articles