如果它等于某值,则更改数组值之一

时间:2018-06-28 02:14:48

标签: php

我正在使用explode() php函数将句子划分并将其转换为用户在不同页面上的输入字段中填写的数组。从该句子中,我需要确定是否存在该单词,并且在其中添加<b></b>。我尝试过:

$wordsentence = explode(' ', $wordsentence);
$place == '0';
foreach ($wordsentence as $ws) {
    if ($ws == $word) {
        $word = '&lt;b&gt;'.$word.'&lt;/b&gt;';
        $save = $place;
    }
$place++;
}

,但同一句子中可能有多个单词。有什么办法可以标记多个单词?

1 个答案:

答案 0 :(得分:0)

您的初始设置:

$wordSentence = "This is a sentence, made up of words";
$wordTest = "made";
$wordsArr = explode(' ', $wordSentence);

我将foreach循环换成标准的for循环,这样我们就不需要初始化单独的索引变量并对其进行跟踪。

for ($i = 0; $i < count($wordsArr); $i++) {
    if ($wordsArr[$i] == $wordTest) {
        $boldWord = '<b>' . $wordTest . '</b>';
        //take your wordsArray, at the current index,
        //swap out the old version with the bold version
        array_splice($wordsArr, $i, 1, $boldWord);
    }
}

并完成我们的测试:

$boldedSentence = implode(' ', $wordsArr);
echo $boldedSentence . "\n";

输出:

> This is a sentence, <b>made</b> up of words