开发者

Help with str_replace()

I'm cleaning a string removing strings in this array:

$regex = array("subida", " de"," do", " da", "em", " na", " no", "blitz");

And this is the str_replace i'm using:

for($i=0;$i<8;$i++){
    $twit = str_repl开发者_JAVA百科ace($regex[$i],'', $twit);
}

how do I make it only remove a word if it's exactly the word in string, I mean, I have the following phrase: "#blitz na subida do alfabarra blitz" it will return me: "# alfabarra", I don't want the first "blitz" to be removed because it has a hash "#", i want it to output: "#blitz alfabarra", is it possible ? thanks


This assumes that none of your strings have / in them. If so, run preg_quote() explicitly with / as the second argument.

It also assumes you want to match the words, so I trimmed each word.

$words = array("subida", " de"," do", " da", "em", " na", " no", "blitz");

$words = array_map('trim', $words);

$words = array_map('preg_quote', $words);

$str = preg_replace('/\b[^#](?:' . implode('|', $words) . ')\b/', '', $str);

Codepad.


After failing to come up with a catch-all regex solution, the following may be useful:

$words = array("subida", " de", " do", " da", "em", " na", " no", "blitz");
$words = array_map('trim', $words);

$str = '#blitz *blitz ablitz na subida do alfabarra blitz# blitz blitza';

$str_words = explode(' ', $str);
$str_words = array_diff($str_words, $words);
$str = implode(' ', $str_words);
var_dump($str);

Gets round a few complications with word boundaries in regex-based solutions.


Try this:

for($i=0; $i<$regex('count'); $i++){
    foreach($regex[$i] as $key) {
        if ( is_string($key) ) {
            $twit = str_replace($regex[$i],'', $twit);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜