我有像这样的php数组
$values = array(
"hello" => "12",
"a" => "24",
"grand" => "40",
"mother" => "10"
);
例如,和一个字符串
$string = "<p>hello</p><div style="align:center"> i am a grand mother</span>";
初始文本可以包含html代码。这一点很重要。
我需要替换字符串中的所有单词
<span id="word_id">word</span>
在我的例子中,结果将是:
<p>
<span id="12">hello</span>
</p>
<div style="align:center">i am
<span id="24">a</span>
<span id="40">grand</span>
<span id="10">mother</span>
</div>
主要问题是它可以用于基本的string_replace,因为它将替换单词&#34; a&#34;用词&#34; grand&#34;例如 。 另外一件事,我需要在我的文本上保留初始的html代码。 而且我不知道我是否可以浏览我的字符串文本,如果存在单词则逐字逐句替换。
答案 0 :(得分:3)
你不需要这里的正则表达式。 PHP有一个标记字符串的功能(将它们分成更小的字符串)
此方法还使用array_keys()
返回$values
数组中的键数组。
<?php
$values = array(
"hello" => "12",
"a" => "24",
"grand" => "40",
"mother" => "10"
);
$string = "hello I am a grand mother";
$token = strtok($string, " ");
$newString = '';
while ($token !== false) {
if (in_array($token, array_keys($values))) {
$newString .= "<span id='" . $values[$token] . "'>". $token . "</span> ";
} else {
$newString .= " " . $token . " ";
}
$token = strtok(" ");
}
echo $newString;
?>
答案 1 :(得分:1)
这是我的解决方案:
<?php
$string = "hello i am a grand mother";
$values = array(
"hello" => "12",
"a" => "24",
"grand" => "40",
"mother" => "10"
);
foreach($values as $word=>$id){
$string = preg_replace("/(\s|^)$word(\s|$)/","$1<span id=\"$id\">$word</span>$2",$string);
}
echo $string;
答案 2 :(得分:1)
虽然制定了一个解决方案。但这是:
$exp = explode(' ', $string);
foreach ($exp as $e) {
if (array_key_exists($e, $values))
{
$a = "<span id=\"".$values[$e]."\">".$e."</span>";
}
else
{
$a = $e.' ';
}
$result .= $a;
}
echo $result;
答案 3 :(得分:0)
使用explode()尝试此代码,计算字符串字,并使用in_array条件创建for循环。
app.connection.query('UPDATE ITEMS.ITEMS_TABLE SET item_isdeleted=1 WHERE id=' + req.query.item_id,
function(err, rows){
if(err){
console.log('error occured in deleting: code - ' + err.code + " ,isFatal - " + err.fatal);
// Send error message with status as "failure" or smth explanatory
res.send({"status": "failure", "message": 'error occured in deleting: code - ' + err.code + " ,isFatal - " + err.fatal });
} else {
res.send({"status": "success", "message": "Item deleted with id - " + req.query.item_id });
}
});
Outpur
$values = array(
"hello" => "12",
"a" => "24",
"grand" => "40",
"mother" => "10"
);
$string = "
hello
i am a grand mother";
$string = preg_replace('/\s+/', ' ', $string);
$stringExp = explode(" ", $string);
$len = count($stringExp);
$newString = '<p>';
for($i=0; $i<$len;$i++){
if (in_array($stringExp[$i], array_keys($values))) {
$newString .= "<span id='" . $values[$stringExp[$i]] . "'>". $stringExp[$i] . "</span> ";
} else {
$newString .= " " . $stringExp[$i] . " ";
}
if ($i == 1) {
$newString .= '</p><div style="align:center">';
} else if ($i == $len - 1) {
$newString .= "</div>";
}
}
echo $newString;