【问题标题】:PHP regex on string字符串上的PHP正则表达式
【发布时间】:2011-11-27 08:54:56
【问题描述】:

我有这个小代码来提取#hashtags

$text = 'The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. #lorem #ipsum #another#tags';
$content  = explode(' ', $text);
$tags = array();
foreach ($content as $item){
    if (preg_match('/#([^\s]+)/', $item, $matches)) {
        $tags[]= $matches[0];
    }
}

得到了这个:

Array(
    [0] => #lorem
    [1] => #ipsum
    [2] => #another#tags
)

问题是:我如何才能匹配#another#tags 并附加到我当前的数组?

新问题:一些文本有像 http://someurl.com/here.html#top 这样的 url,#top 部分也像标签一样被解析。有什么办法可以避免吗?

【问题讨论】:

  • 你的意思是你想要四个标签:#lorem、#ipsum、#another 和#tags?
  • Twitter 主题标签中间不能有 #。事实上,他们只能拥有[a-zA-Z]{1}[a-zA-Z0-9]*。更新您的正则表达式应该可以解决您面临的问题。

标签: php regex


【解决方案1】:

如果你想要做的只是拉出所有的哈希标签,那么你可以简单地这样做:

$text = 'The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. #lorem #ipsum #another#tags';
preg_match_all("/\#\\w+/", $text, $matches);
$tags = $matches[0];

【讨论】:

  • 在 # 之前添加一个外观,例如: (?
【解决方案2】:

正则表达式1/#([^(\s#)]+)/

正则表达式2/#([^\s^#)]+)/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多