我有一个这样的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因为它会替换单词"grand"中的单词"a"。另一件事,我需要在我的文本上保留初始 html 代码。而且我不知道我是否可以浏览我的字符串文本并在单词存在时逐字替换。
这里不需要正则表达式。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;
?>
这是我
的解决方案:
<?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;
虽然做了
一个解决方案有点晚了。在这里:
$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;
使用 explode() 尝试此代码,计算字符串单词并使用in_array条件创建 for 循环。
$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;
外出
//<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>