假设我有以下数组(这是数据库查询的返回值):
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
实例:
关于php - 如何: compare array with string and create hastags before tweeting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4583021/