PHP:字符串格式替换并添加字符

时间:2010-09-22 23:58:55

标签: php string

我有这段代码:

$array[] = "<b>  FLYDANNA&reg; HEADWRAP  </b>     <ul>  <li type=\"circle\"><i>  Sensational headwrap made from 6 pieces of fabric to fit the contours of your head perfectly  </i>  <li type=\"circle\"><i>  Strong yet lightweight cotton wrap can be folded up and stored almost anywhere-;pocket, purse, backpack ... you name it!  </i>  <li type=\"circle\">";

我想删除所有的html标签,删除多余的空格,并在最后一个大写字后添加一个双短划线。此外,在每个</li>标记后,我将添加一个句点。

我需要在将它放入数组之前对其进行格式化,因此输出必须为:

$array[] = "FLYDANNA&reg; HEADWRAP-- Sensational headwrap made from 6 pieces of fabric to fit the contours of your head perfectly. Strong yet lightweight cotton wrap can be folded up and stored almost anywhere-;pocket, purse, backpack ... you name it!";

提前致谢:)

1 个答案:

答案 0 :(得分:3)

鉴于以下内容:

$str = "<b>  FLYDANNA&reg; HEADWRAP  </b>     <ul>  <li type=\"circle\"><i>  Sensational headwrap made from 6 pieces of fabric to fit the contours of your head perfectly  </i>  <li type=\"circle\"><i>  Strong yet lightweight cotton wrap can be folded up and stored almost anywhere-;pocket, purse, backpack ... you name it!  </i>  <li type=\"circle\">";

这段代码可以解决问题:

$str = strip_tags( $str );
$str = preg_replace( '/\s+/', ' ', $str );
$words = array_reverse( explode( ' ', $str ) );
foreach ( $words as $k => $s ) {
  if ( preg_match( '/\b[A-Z]{2,}\b/', $s ) ) {
    $words[$k] = $s . "--";
    break;
  }
}

$str = trim( join( ' ', array_reverse( $words ) ) );