-4

我有一系列 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 标签包装每个“测试”值?

4

2 回答 2

1
foreach ($array as $stdClass)
    foreach ($stdClass as &$value) // reference
        if ($value === "test")
            $value = "<span>".$value."</span>";

只需遍历数组和类,因为它们都可以使用 foreach 进行迭代。(通过引用迭代类,否则它不会改变)

于 2013-04-10T15:30:36.617 回答
0

要将与单词“test”匹配的所有对象值包装在一个跨度中,您需要遍历对象属性以及数组本身。您可以使用 foreach 执行此操作:

foreach ($object in $array) {
    foreach ($property in $object) {
        if ($object->$property == 'test') {
            $object->$property = "<span>{$object->property}</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 purpose as a test”,上面的调用将输出:

This <span>test</span> is for testing purposes as a <span>test</span>.
于 2013-04-10T15:37:04.743 回答