这可能使用PHP吗?

时间:2011-06-23 00:58:57

标签: php html

好的,所以说我有一个WordPress帖子,某些单词包含在span标签中。

例如:

<p>John went to the <span>bakery</span> today, and after picking up his favourite muffin     he made his way across to the <span>park</span> and spent a couple hours on the <span>swings</span> with his friends.</p>

然后是一种使用PHP动态吐出它们(span标签中的单词)作为模板文件中的有序列表的方法吗?

像这样:

<h3>What John Did Today</h3>
<ol>
<li>bakery</li>
<li>park</li>
<li>swings</li>
</ol>

如果有人能指出如何做这样的事情的正确方向,那将非常感激。谢谢。

4 个答案:

答案 0 :(得分:5)

$str = '<p>John went to the <span>bakery</span> today, and after picking up his favourite muffin     he made his way across to the <span>park</span> and spent a couple hours on the <span>swings</span> with his friends.</p>';

$d = new DomDocument;
$d->loadHTML($str);

$xpath = new DOMXPath($d);
echo "<h3>What John Did Today</h3>\n";
echo "<ol>\n";
foreach ($xpath->query('//span') as $span)
  echo "<li>".$span->nodeValue."</li>\n";
echo "</ol>\n";

答案 1 :(得分:0)

一种简单的可能性是使用正则表达式take a look at preg_match function

答案 2 :(得分:0)

答案 3 :(得分:0)

我不是正则表达式,但是应该用<span>标签替换<li>标签:

$str = preg_replace("/<span>([^[]*)<\/span>/i", "<li>$1</li>", $str);

..我知道这不会直接回答你的问题,但它应该在某些时候帮助你lol

编辑:完整的实际工作正则表达式解决方案,用于将所有span标记放入数组并同时转换为列表项:

// input string:
$str = '<span>Walk</span> blah <span>Drive</span> blah blee blah <span>Eat</span>';

// get array of span matches
preg_match_all("/(<span>)(.*?)(<\/span>)/i", $str, $matches, PREG_SET_ORDER);

// build array using the exact matches
foreach($matches as $val){
    $spanArray[] = preg_replace("/<span>([^[]*)<\/span>/i", "<li>$1</li>", $val[0]);
}

如果你然后print_r($spanArray);你应该得到这样的东西:

Array
(
    [0] => <li>Walk</li> 
    [1] => <li>Drive</li> 
    [2] => <li>Eat</li> 
)