我有stdClass数组:
array (size=2)
0 =>
object(stdClass)[2136]
public 'id' => string '1946' (length=4)
public 'office' => string 'test' (length=4)
public 'level1' => string 'test level 1' (length=12)
1 =>
object(stdClass)[2135]
public 'id' => string '1941' (length=4)
public 'office' => string 'test' (length=4)
如何用span标记包装每个'test'值?
答案 0 :(得分:1)
foreach ($array as $stdClass)
foreach ($stdClass as &$value) // reference
if ($value === "test")
$value = "<span>".$value."</span>";
简单地遍历数组和类,因为它们都可以使用foreach进行迭代。 (通过引用迭代该类,否则不会更改)
答案 1 :(得分:0)
要在span中包装与“test”一词匹配的所有对象值,您需要遍历对象属性以及数组本身。你可以使用foreach:
来做到这一点foreach ($object in $array) {
foreach ($property in $object) {
if ($object->$property == 'test') {
$object->$property = "<span>{$object->property}</span>";
}
}
}
如果要在带有span的属性值中包装单词test的所有实例,可以使用preg_replace按如下方式执行:
foreach ($object in $array) {
foreach ($property in $object) {
$object->$property = preg_replace('/\b(test)\b/', '<span>$1</span>', $object->$property);
}
}
给定字符串“此测试用于测试目的作为测试”,上述调用将吐出:
This <span>test</span> is for testing purposes as a <span>test</span>.