php - 如何: compare array with string and create hastags before tweeting

标签 php arrays

假设我有以下数组(这是数据库查询的返回值):

Array ( [0] => PHP [1] => Webdesign [2] => Wordpress [3] => Drupal [4])

以及以下字符串:

Working With Wordpress Shortcodes

如何将数组与字符串进行比较,以查看字符串是否包含存储在数组中的任何单词? (希望这对你有意义 :d )

当他找到匹配项(例如:Wordpress)时,它应该创建一个标签,如下所示:

Working With #Wordpress Shortcodes

最佳答案

使用preg_replace:

$tags = array('PHP', 'Webdesign', 'Wordpress', 'Drupal', 'SQL');
$text = 'Working With Wordpress Shortcodes and doing some NoSQL and SQL';

$regex = '/\b('.implode('|', array_map('preg_quote', $tags)).')\b/i';
$result = preg_replace($regex, '#$1', $text);

会输出:

Working With #Wordpress Shortcodes and doing some NoSQL and #SQL

实例:

http://codepad.org/SxchtXmI

关于php - 如何: compare array with string and create hastags before tweeting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4583021/

相关文章:

Javascript排序数组会改变窗口对象,但在迭代它时不会改变

java - 替换存储在字符串数组中的换行符

php - PHP 对象序列化有多安全,跨页面传递是否安全? (使用 phpXMLrpc)

PHP选择带权重的随机数

php - 增加我的 PHP 脚本的上传限制

php - 将变量的值附加到变量名称?

javascript - 如何根据特定的 JSON 对象值对数组进行计数?

javascript - 如何插入多维数组javascript

arrays - Powershell:从get-wmiobject win32_product过滤不需要的值

php - 更好地建立数据库结构