我有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'值
foreach ($array as $stdClass)
foreach ($stdClass as &$value) // reference
if ($value === "test")
$value = "<span>".$value."</span>";
简单地遍历数组和类,因为它们都可以用foreach迭代。(通过引用迭代类,否则不会更改)
要在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 test is for testing purposes as a test",上述调用将输出如下内容:
This <span>test</span> is for testing purposes as a <span>test</span>.