我需要帮助才能找到文本中的字符串,该文本以@
开头,直到preg_match
在php中的下一个直接空格
Ex:我想从这一行获取@string作为单独的。 在这个例子中,我需要提取" @ string"从这条线上独自一人。
任何机构都可以帮我找到解决办法。
提前致谢!
答案 0 :(得分:1)
PHP和Python在搜索方面并不相同。如果你已经在捕获中使用了strip_tags
这样的函数,那么像这样的东西可能比其他一个答案中提供的Python示例更好,因为我们也可以使用look-around assertions。
<?php
$string = <<<EOT
I want to get @string from this line as separate.
In this example, I need to extract "@string" alone from this line.
@maybe the username is at the front.
Or it could be at the end @whynot, right!
dog@cat.com would be an e-mail address and should not match.
EOT;
echo $string."<br>";
preg_match_all('~(?<=[\s])@[^\s.,!?]+~',$string,$matches);
print_r($matches);
?>
输出结果
Array
(
[0] => Array
(
[0] => @string
[1] => @maybe
[2] => @whynot
)
)
如果您直接从HTML流本身拉出来,那么查看Twitter HTML,它的格式如下:
<s>@</s><b>UserName</b>
因此,为了匹配html流中的用户名,您将匹配以下内容:
<?php
$string = <<<EOT
<s>@</s><b>Nancy</b> what are you on about?
I want to get <s>@</s><b>string</b> from this line as separate. In this example, I need to extract "@string" alone from this line.
<s>@</s><b>maybe</b> the username is at the front.
Or it could be at the end <s>@</s><b>WhyNot</b>, right!
dog@cat.com would be an e-mail address and should not match.
EOT;
$matchpattern = '~(<s>(@)</s><b\>([^<]+)</b>)~';
preg_match_all($matchpattern,$string,$matches);
$users = array();
foreach ($matches[0] as $username){
$cleanUsername = strip_tags($username);
$users[]=$cleanUsername;
}
print_r($users);
<强>输出强>
Array
(
[0] => @Nancy
[1] => @string
[2] => @maybe
[3] => @WhyNot
)
答案 1 :(得分:0)
只需简单地做:
preg_match('/@\S+/', $string, $matches);
结果位于$matches[0]