代码之家  ›  专栏  ›  技术社区  ›  marknt15

字符串格式替换和添加字符

  •  0
  • marknt15  · 技术社区  · 14 年前

    $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 回复  |  直到 14 年前
        1
  •  3
  •   Jim    14 年前

    $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 ) ) );