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


Remove word only for first line using 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

下面将找到第一行,将该行的"blue"字替换为空(删除它),去掉标记并删除前导/尾随空格。

  • 只删除整个单词,例如"blues"中的"blue"
  • 如果在第一行中找不到单词,将不会从后面的行中删除
  • 不会从以下行中剥离标记

代码:

$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