我需要帮助找出php 中从@
开始到preg_match
的下一个直接空格的文本中的字符串
我想从这行得到@string作为分隔符。在这个例子中,我需要从这行中单独提取"@string"。
有谁能帮我找出解决这个问题的办法吗。
提前感谢!
PHP和Python在搜索方面不同。如果您已经在捕获中使用了strip_tags
这样的函数,那么这样的函数可能比其他答案中提供的Python示例更好,因为我们也可以使用环视断言。
<?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
)
只需简单操作:
preg_match('/@'S+/', $string, $matches);
结果在$matches[0]
中