3

我正在使用 PHPstrpos()在一段文本中查找针。我正在为找到针后如何找到下一个单词而苦苦挣扎。

例如,考虑以下段落。

$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.";

我可以strpos($description, "SCREENSHOT")用来检测 SCREENSHOT 是否存在,但我想在 SCREENSHOT 之后获取链接,即mysite.com/screenshot.jpg. 以类似的方式,我想检测描述是否包含 LINK 然后返回mysite.com/link.html

如何使用strpos()然后返回以下单词?我假设这可能是用正则表达式完成的,但我不确定。下一个词将是“针后的一个空格,然后是任何内容,然后是一个空格”。

谢谢!

4

3 回答 3

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
}
于 2011-02-01T19:55:20.767 回答
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);

我正在使用积极的后视来获得你想要的东西。

于 2011-02-01T19:56:40.423 回答
1

或“旧”方式... :-)

$word = "SCREENSHOT ";
$pos = strpos($description, $word);
if($pos!==false){
    $link = substr($description, $pos+strlen($word));
    $link = substr($link, strpos($link, " "));
}
于 2011-02-01T19:57:52.113 回答