php 从文本 block 中提取所有主题标签和推特名称

标签 php

我在 php 中有一段文本,我希望能够从中提取所有主题标签和推特名称,并将它们打印为一个新字符串。

例如:

$longstring = "blah blah blah #hashtag blah blah @twittername blah email@email.com blah blah #hashtag2 blah blah";

我想创建一个新字符串:

$extracted = "#hashtag @twittername #hashtag2";

知道如何轻松地做到这一点吗?

我不确定答案是否是正则表达式?这是否可以同时进行并找到两种类型的所有多次出现?

最佳答案

希望这对您有所帮助。

Regex demo

正则表达式: #[^\s]+|(?<=\s|^)@[^\s@#]+

1. #[^\s]+ this will match # and then match all till space(not including space)

2. | or

3. (?<=\s|^)@[^\s@#]+ match @ and then all except space, @ and # with positive look behind for space or start of string

这里我们使用 preg_match_all用于收集火柴和 implode将其作为字符串加入。

Try this code snippet here

<?php
ini_set('display_errors', 1);
$string = "blah blah blah #hashtag blah blah @twittername blah email@email.com blah blah #hashtag2 blah blah";
preg_match_all("/#[^\s]+|(?<=\s|^)@[^\s@#]+/", $string, $matches);
print_r(implode(" ",$matches[0]));

输出: #hashtag @twittername #hashtag2

关于php 从文本 block 中提取所有主题标签和推特名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43972708/

相关文章:

php - 如果不存在使用 PDO 添加 MySQL 列

php - 从 MySQL 检索数据到 HTML

php - imap_open : couldn't open stream to my mail server

javascript - 使用 Ajax 单击按钮删除表行

php记录重复值并添加到新数组(多维数组)

PHP 多维数组到平面文件夹 View

php - 谁能帮我弄清楚这段代码有什么问题?

php - 将当前日期存储在数据库中

php - Twig 中 escape ('html' ) 和 escape ('html_attr' ) 的区别

php - 在 JQuery 中独立切换两行