正则表达式找到&在之前或之后更换; _

时间:2014-11-20 19:28:17

标签: php regex

我正在尝试添加列表。 例如,如果我有这个:

Fits 10" - 24" TVs ;_ Holds up to 80lbs ;_ Mounts to a single wood stud, concrete or cinder block ;_ Low-profile design holds screen less than 1" from the wall ;_

问题1:如何在<li>之前和</li>之后添加; {with regex
就这样:

<ul>;_  <li>Fits 10" - 24" TVs</li>;_   <li>Holds up to 80lbs</li>;_    <li>Mounts to a single wood stud, concrete or cinder block</li>;_   <li>Low-profile design holds screen less than 1" from the wall</li>;_   </ul>'

问题2:如果可能或(如果需要),如何在列表末尾的<ul></ul>处。

2 个答案:

答案 0 :(得分:0)

你不需要正则表达式。使用explode

$string = 'Fits 10" - 24" TVs ;_ Holds up to 80lbs ;_ Mounts to a single wood stud, concrete or cinder block ;_ Low-profile design holds screen less than 1" from the wall ;_';
$items = expode(';_', $string);
echo '<ul>';
foreach ($items as $item) {
    if (!empty(trim($item)) { // This may throw an error if your PHP version is old
        echo '<li>' . $item . '</li>';
    }
}
echo '</ul>';

答案 1 :(得分:0)

使用跟随:

$s =  ".. ;_ ..";
$list = explode(';_', $s);
$html = "<ul><li>".implode('</li><li>', $list)."</li></ul>";

甚至:

echo "<ul><li>".implode('</li><li>', explode(';_', ".. ;_ .."))."</li></ul>";

看起来像常规;)

添加

在伪代码中,因为我不知道您正在使用的数据库API。

  if (!($q = $db->query("SELECT id, html FROM wp_table_name"))) {
    throw new Exception("No rows returned");
  }
  $rows = array();
  while ($row = $q->fetch_object()) {
    $db->query("UPDATE wp_table_name SET html = ? WHERE id = ?", array(
      "<ul><li>".implode('</li><li>', explode(';_', $row->html))."</li></ul>",
      $row->id
    ));
  }