首页 > 解决方案 > 在数组中指定的单词之后添加

问题描述

我想 在我在数组中定义的单词之后添加。所以我希望它出来:Testing w it's ul. here。请帮忙。我不知道该怎么做。

$array = array('w','z','u','o','ul.');
$titleOld = 'Testing w it's ul. here';
$title = str_replace($array.' ',' ',$titleOld);

编辑:我做这样的事情:

$nbspBefore = array(' w ',' z ',' u ',' o ',' ul. ');
$nbsp = array(' w ',' z ',' u ',' o ',' ul. ');
$title = 'Testing w it's ul. here';
$title = str_replace($nbspBefore,$nbsp,$title);

我认为这不是干净的代码,但它工作正常。

编辑 2:好的,我用另一种方式,在 JS 中。

var array=['w','z','u','o','ul.'],
    text = document.querySelector('selector');
for(i=0;i<array.length;i++){
    text.innerHTML = text.textContent.replace(new RegExp(' '+array[i]+' ','g'),' '+array[i]+'&nbsp;');
}

标签: javascriptphparrays

解决方案


尝试 :

$search = array('w ', 'z ', 'u ', 'o ', 'ul. ');
$replace = array('w&nbsp;', 'z&nbsp;', 'u&nbsp;', 'o&nbsp;', 'ul.&nbsp;');
$titleOld = "Testing w it's ul. here";
$title = str_replace($search, $replace, $titleOld);

https://www.php.net/manual/fr/function.str-replace.php,第一个例子,第三种情况)


推荐阅读