如何:将数组与字符串进行比较并在发布之前创建主题标签

时间:2011-01-03 08:29:18

标签: php arrays

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

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

以下字符串:

  

使用Wordpress短代码

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

当他找到一个匹配项(例如:Wordpress)时,它应该创建一个像这样的标签:

  

使用#Wordpress Shortcodes

6 个答案:

答案 0 :(得分:4)

使用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);

输出:

  

使用#Wordpress短代码并执行一些NoSQL和#SQL

实例:

  

http://codepad.org/SxchtXmI

答案 1 :(得分:2)

遍历数组并在字符串上为每个值运行preg_replace(确保检查正则表达式中的单词边界(例如,因此汽车与卡通不匹配)

答案 2 :(得分:2)

只需遍历您的数组并使用strpos()(或其不区分大小写的版本stripos()):

$tags = array('PHP', 'Webdesign', 'Wordpress', 'Drupal');
$message = "Working With Wordpress Shortcodes";

foreach ($tags as $tag) {
    $position = strpos($message, $tag);

    if ($position !== false) {
        // tag found! add # in front.
        $message = substr($message, 0, $position).'#'.substr($message, $position);
    }
}

答案 3 :(得分:0)

<?
$working_array = array('PHP','Webdesign','Wordpress','Drupal');
$string = "Working With Wordpress Shortcodes";
foreach($working_array as $array_item)
{
    $the_pos = stripos($string,$array_item);
    if($the_pos !== false)
    {
        $string = substr($string,0,$the_pos) . '#' . substr($string,$the_pos);
    }
}
echo $string;
?>

编辑因为我不小心混入了一些C语法!遗憾!

答案 4 :(得分:0)

如果您的数组很大,可能需要很长的处理时间(我猜)

$hashtags = array('Wordpress', 'Twitter', 'Joomla', 'Google');
$content = "A tweet containing wordpress and joomla";


$content_breakdown = explode(' ', $content);
foreach ($hashtags as $hashtag) {

    foreach ($content_breakdown as & $word) {
        if (strtolower($word) == strtolower($hashtag))
            $word = '#' . $word;
    }
}

$content = implode($content_breakdown, ' ');
echo $content;

输出

A tweet containing #wordpress and #joomla

答案 5 :(得分:0)

$hashtags = array('Wordpress', 'Joomla', /* ... */ );
$tweet = "This is a tweet containing Wordpress and Joomlazoom as hashtag";

$hashtags_tmp = implode('|', $hashtags);
$tweet = preg_replace("/\b($hashtags_tmp)\b/i", '#$1', $tweet);