2

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:

 $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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Damn... :( It's always the same, I'm thinking way too complex. Thank you!
1

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>";

2 Comments

Keep in mind that the text at the end of the string will almost certainly not be followed by a <br> tag.
You're right! I didn't thought about it. But with anubhava solution I can add "echo "</li></ul>" so the last one gets closed, too. Thanks for pointing me on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.