PHP RegEx replace

I’m trying to write a PHP Script that replaces auto-generated Content from a WordPress Plugin. The Plugin isn’t able to provide a WYSIWYG Editor for special fields but it can recognize new lines. My Output would look like this:

Some Text that has to
go over a few
lines of code
because it's actually supposed to be a list

when the client writes inside these field all lines get <br> tags at the end, so I tried to find and replace them with </li> tags as well as adding a <li> in front of every new line. My PHP Script looks like this:

Read More
 $text = types_render_field("field-name");

 $pattern = array();
 $pattern[0] = "/br/"; // br tags
 $pattern[1] = "/n/"; // new lines
 $replacements = array();
 $replacements[0] = "/li"; // replacement for <br>
 $replacements[1] = "<li>"; // insert into every new line (n)

 echo "<ul>"; // wrapping the <li>'s
 echo preg_replace($pattern, $replacements, $text);
 echo "</ul>";

It’s actually working so far but the first line get’s no <li> in front of it so my question is: How do I get a <li> in front of the first line?

Related posts

Leave a Reply

2 comments

  1. Keep it simple. Instead of

    echo "<ul>"; // wrapping the <li>'s
    

    Use:

    echo "<ul><li>"; // wrapping the <li>'s
    

    OR else:

    Instead of:

    $pattern[1] = "/n/"; // new lines
    

    Use:

    $pattern[1] = "/^|n/"; // new lines OR start
    
  2. How about:

    $pattern = "/(.+?)(<br>|$)/i"; // capture the text before the br tag
    $replacement = "<li>$1</li>"; 
    echo "<ul>"; 
    echo preg_replace($pattern, $replacement, $text);
    echo "</ul>";