检查字符串以查看它是否包含数组中的一个字符串

时间:2014-04-17 10:29:02

标签: php arrays regex

整个上午都在摸不着头脑,似乎没有想到一个合乎逻辑的快速方法,不使用大量资源。

这是方案,

$content = "hello this is a lovely website that people help me with and i love it";
$arrayto = array("good morning","hello","good afternoon","morrow");
$website = "http://www.google.com";

我想检查$ content,如果它包含一个数组单词,如果它确实将$website作为href=""转换为链接,然后立即停止它找到了一个。

那么$content就是"<a href="$website">hello</a> this is a lovely website that people help me with and i love it";

由于

5 个答案:

答案 0 :(得分:1)

来源link str_replace可能是一个答案

// Provides: You should eat pizza, beer, and ice cream every day
    $phrase  = "You should eat fruits, vegetables, and fiber every day.";
    $healthy = array("fruits", "vegetables", "fiber");
    $yummy   = array("pizza", "beer", "ice cream");

    $newphrase = str_replace($healthy, $yummy, $phrase);

答案 1 :(得分:0)

这样做 -

<?php

$content = "hello this is a lovely website that people help me with and i love it";
$arrayto = array("good morning","hello","good afternoon","morrow");
$website = "http://www.google.com";

$data=explode(' ', $content);
$final=array();

foreach ($data as $key ) {

    if(array_search($key, $arrayto))
    {
        $word='<a href='.$website.'>'.$key."</a>";
        array_push($final, $word);
    }
    else
    {
      array_push($final, $key);
    }
}

$res=implode(' ', $final);

print_r($res);

?>

OUTPUT- hello这是一个可爱的网站,人们帮助我,我喜欢它

答案 2 :(得分:0)

使用str_replace

可以不使用正则表达式
 <?php
    $content = "hello this is a lovely website that people help me with and i love it";
    $arrayto = array("good morning","hello","good afternoon","morrow");
    $website = "http://www.google.com";

    foreach($arrayto as $v){
     if(strpos($content,$v)!==false){
   $content= str_replace("$v","<a href=$website>$v</a>",$content);
        }
    }
    echo $content;

DEMO

<强>输出

<a href=http://www.google.com>hello</a> this is a lovely website that people help me with and i love it

答案 3 :(得分:0)

$content = "hello this is a lovely website that people help me with and i love it";
$arrayto = array("good morning","hello","good afternoon","morrow");
$website = "http://www.google.com";
while($item = each($arrayto)){
    if(strstr($content, $item['value'])!==false){
        $content = str_replace($item['value'], '<a href="'.$website.'">'.$item['value'].'</a>', $content);
        break;
    }
}

您可以使用功能strstr

答案 4 :(得分:0)

这可以通过有效的方式解决,而无需使用preg_replace

进行循环
$content = "hi hello and bye";
$words = array('hello', 'bye');
$website = "http://www.google.com";

$regex = '/\b(' . implode('|', $words) . ')\b/';
echo preg_replace($regex, "<a href='$website'>$1</a>", $content, 1);

请注意,如果您只想替换整个单词,则必须使用正则表达式和\b位,否则会将helloween变为<a...>hello</a>ween