仅使用php删除第一行的单词

时间:2015-04-07 12:32:23

标签: php

我有文字:

I have new blue car
I have new red and blue cars

如何使用php从第一行删除我想要的单词?

例如:

        $text = preg_replace("/^(blue>){1}/", "", $text);

结果应为:

I have new car
I have new red and blue cars

我想要删除" p br"它是可行的。

<p></p><br/>I have new blue car
I have new red and blue cars

1 个答案:

答案 0 :(得分:0)

以下内容将找到第一行,将该行上的“蓝色”字替换为空(删除),剥离标记并删除前导/尾随空格。

  • 只删除整个字词,例如“蓝调”中不是“蓝色”
  • 如果在第一行找不到,则不会删除以下行中的字词
  • 不会从以下行中删除标记

代码:

$text = "<p></p><br/>I have new blue car
I have new <b>red<b> and blue cars";
$word = 'blue';

$text = preg_replace_callback(
    '/.*$/m', // Match single line
    function ($matches) use ($word) {
        // Remove word (\b = word boundary), strip tags and trim off whitespace
        return trim(
            strip_tags(
                preg_replace('/\b' . $word. '\s*\b/', '', $matches[0])
            )
        );
    },
    $text,
    1 // Match first line only
);

echo $text, PHP_EOL;

输出:

I have new car
I have new <b>red<b> and blue cars