PHP replace div with some class to p with addtional attribute

Kamarul Anuar asked
php replace preg-replace str-replace
via

currently I used preg_raplace, I try to replace all p tag with class="para" to div with addtional attribute.. the problerm; it’s not change all of p tag with class="para" .

My codes in PHP FIDDLE FOR LIVE TEST.

And below is my codes.

    <?php

// your code goes here

$content = '
<p class="para">My first paragraph</p>

<p class="para">bansbnabsna</p>

<p class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non augue vitae elit vehicula condimentum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius nunc massa, id dictum urna auctor nec. Cras ut urna at sapien volutpat interdum posuere sed metus. Duis vel egestas turpis. Mauris maximus aliquam pellentesque. Mauris dapibus nisi non ante aliquet pretium. Cras vitae nisi pellentesque, ullamcorper nisi vitae, malesuada ante. Phasellus scelerisque congue diam ac cursus. Nullam arcu leo, condimentum sit amet elementum in, blandit blandit dui. Phasellus dignissim, nibh non aliquet facilisis, augue urna porta odio, eu porta neque purus a purus. Sed sollicitudin ut magna vitae lacinia. Mauris venenatis justo nisi, nec interdum nisl lobortis non. Aenean a dictum nisi, sed mollis massa. Praesent ut aliquet dui.
</p>

<p class="para">Nulla et tristique erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer volutpat nibh bibendum condimentum elementum. Duis tempor porta lobortis. Aenean mollis diam a justo condimentum, in iaculis leo ornare. Quisque ultrices pulvinar tortor a tempor. Ut et finibus ipsum. Vivamus nec interdum magna. Fusce dignissim laoreet libero sit amet lacinia. Mauris varius erat odio, a porta sapien pulvinar ut. Aliquam pretium arcu at nulla lobortis, eu ultrices ipsum porta. Quisque viverra ullamcorper elit ac scelerisque. Phasellus scelerisque laoreet laoreet. Nulla mattis sed ligula nec tempor. Vivamus condimentum nisi sit amet congue molestie. Nunc posuere id tellus et tincidunt.
</p>

<p class="para">Etiam sodales magna dui, et suscipit erat egestas non. Integer a malesuada nunc. Sed pharetra justo nec odio posuere, quis pellentesque massa fringilla. Donec dui metus, porttitor eget lacinia eget, consequat in est. Vestibulum id sapien quis est ultrices rutrum at id purus. Duis ac odio a metus ultricies varius sed a neque. Vestibulum porttitor tortor consequat fermentum viverra. Quisque convallis ex eu risus placerat tempus at vitae leo. Sed vel ante sit amet justo rhoncus convallis. Praesent lobortis lobortis fermentum. Sed sapien velit, bibendum aliquam nibh vitae, porttitor egestas odio.
</p>

<p class="para">Aliquam fermentum arcu nec dapibus dictum. Duis egestas turpis eu finibus ullamcorper. Fusce dictum sed leo hendrerit pretium. Morbi finibus sem tortor, at tristique mauris sodales placerat. Vestibulum auctor, nisi et pellentesque porttitor, lectus leo facilisis turpis, in iaculis ligula arcu eget urna. Vestibulum fermentum luctus lobortis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nam rhoncus mollis consectetur. Fusce sagittis eros lacus, eu aliquam nisi ultricies ac. Sed sit amet lacinia ante. Quisque congue, tortor ac pretium volutpat, nisi nisi laoreet elit, id condimentum ex sapien at urna. Cras sollicitudin malesuada commodo. Integer rutrum sapien non lacinia lacinia. Sed aliquet massa vel erat auctor, quis malesuada felis mollis.
</p>

<p class="para">Proin eu ipsum sem. Sed sagittis arcu nec justo pulvinar, a suscipit magna pulvinar. Nullam ullamcorper est nec dui fringilla, ullamcorper ornare massa semper. Nulla sed ipsum lacus. Vivamus ut imperdiet magna. Nullam nec malesuada quam. Duis facilisis quis lorem eget laoreet. Fusce quis leo ultricies, ullamcorper diam eget, iaculis magna. Nulla nec nisi sit amet arcu dignissim suscipit a eget felis. Sed sagittis accumsan cursus. Mauris pharetra nunc ex, in dignissim lectus mattis et. Maecenas sit amet velit ac nisl fringilla rhoncus vitae a quam. Praesent in placerat nisi. Maecenas suscipit, odio non pretium pellentesque, tortor metus commodo nibh, faucibus egestas urna ex sit amet magna. Sed aliquet, mi non faucibus bibendum, erat eros consectetur dolor, vitae iaculis magna sem eget leo. Aliquam quis lorem finibus turpis pellentesque pulvinar.</p>
';

function format_content_as_editor($str){
    if($str){
      return
      //preg_replace('/(rn|n|r){3,}/', "$1$1",
      str_replace('<br/>', '',
      str_replace('<br>', '',
      preg_replace('/<p [^<]*?class="([^<]*?para.*?)">(.*?)</p>/','<div class="$1" contenteditable="true" autocomplete="off">$2</div>',
      $str
      )
      )
      //)
      );
   } else {
      return  '<div class="para" contenteditable="true" autocomplete="off">Start writing..</div>';
   }
  }

  print_r(format_content_as_editor($content));


Answer
via

The reason it’s not working is because there are line breaks inside some of the HTML markup you’re testing against, and the .* in your regular expression is not matching vertical whitespace (line breaks). To fix, Add the /s modifier to your regular expression. See: http://php.net/manual/en/reference.pcre.pattern.modifiers.php

s (PCRE_DOTALL) If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl’s /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

Here is a slightly cleaner version of your function with the /s modifier, and also the /i modifier, so that it’s not a caSe-sensitive match either, because HTML tag caSe should not be considered, at HTML tags are not caSe-sensitive. Thus, the two modifiers together are /is

<?php
function format_content_as_editor($str)
{
    $str = trim((string) $str);

    if (!$str) { // If empty.
        return  '<div class="para" contenteditable="true" autocomplete="off">Start writing..</div>';
    }
    // Strip <br>, <BR>, <Br>, <br/>, <br />, etc.
    $str = preg_replace('/<brs*/?>/i', '', $str);

    // Replace all <p class="para" ...>[content]</p>.
    $str = preg_replace('/<ps+classs*=s*(["'])para\1([^>]*)>(.*?)</p>/is', '<div class="para"$2 contenteditable="true" autocomplete="off">$3</div>', $str);

    return $str;
}

So you can either use my code, or simply alter your own function to this:

function format_content_as_editor($str){
    if($str){
      return
      //preg_replace('/(rn|n|r){3,}/', "$1$1",
      str_replace('<br/>', '',
      str_replace('<br>', '',
      preg_replace('/<p [^<]*?class="([^<]*?para.*?)">(.*?)</p>/s','<div class="$1" contenteditable="true" autocomplete="off">$2</div>',
      $str
      )
      )
      //)
      );
   } else {
      return  '<div class="para" contenteditable="true" autocomplete="off">Start writing..</div>';
   }
  }

To spotlight the regex pattern with /s flag for you:
'/<p [^<]*?class="([^<]*?para.*?)">(.*?)</p>/s'

Share This
Posted in: