如何在字符串中找到子字符串,如果为真,在PHP中插入文本


How to Find a substring in a srting and if true insert text inbetween in PHP?

我想在给定字符串中搜索特定的子字符串,如果找到,我想在PHP中简单地在这些字符串之间插入一些文本。

我使用了strpos

$text = "Something wordpress"
if(strpos($text,'wordpress',true) !== FALSE)
{
  //Insert <br/> text
}

但不知道如何在字符串之间插入文本。

示例输出

Something <br/> Wordpress

$text = "Something wordpress";
if(strpos($text,'wordpress',true) !== FALSE)
{
    $pos = strpos($text,'wordpress',true);
    $text = substr($text, 0, $pos) . "new text " . substr($text, $pos);
}
echo $text;

尝试使用"str_replace" (http://php.net/manual/en/function.str-replace.php).

例如:

            $text  = "Something wordpress";
            $searchText = "wordpress";
            $replaceText = "different text";
            $newPhrase = str_replace($healthy, $replaceText, $text);
$text = "Something wordpress";
if(strpos($text,'wordpress') !== false)
{
 str_replace('wordpress', '<br>wordpress', $text);
}
$text = "Something wordpress";
if(strpos($text,'wordpress') !== false)
{
  str_replace('wodrpress', ' your text ' . 'wordpress', $text);
}

这样做

echo str_replace('wordpress', '<br>wordpress', 'Something wordpress');

我想知道为什么没有人提到substr_replace的插入…

$text = "Something wordpress";
$pos = strpos($text,'wordpress');
if($pos !== FALSE)
{
    $text = substr_replace($text, "<br>", $pos, 0);
}
var_dump($text); // "Something <br>wordpress"

您可以使用preg_match。此preg_match将搜索'wordpress'并将其替换为'
wordpress'。

$search = 'wordpress';
$string = preg_replace('/' . preg_quote($search, '/') . '/', '<br />$0', $string);

无论我的方法多么有效,我的方法与其他答案没有任何区别。它只是一个字符串替换操作。