John Davidson

php - Regex only matching non-empty newlines

0 comments
Message:


I have a textarea where a user can enter text like this:


**Title 1**
aaa
bbb
ccc

**Title 2**
xxx
yyy
zzz

I convert it to the following result:





Title 1


> aaa

> bbb

> ccc


Title 2

> xxx

> yyy

> zzz




So:



  • Everything between two asterixes gets converted to bold text

  • Every new line gets a > placed before the line


The problem is that the result gets converted to this:





Title 1


> aaa

> bbb

> ccc

>


Title 2

> xxx

> yyy

> zzz

>




Empty new lines also get a >... This should not be the case. How do I filter out all the empty new lines?


Test code:


<html>
<style>
.product-desc-section {
text-transform: uppercase;
font-weight: bold;
font-size: 1em;
}
</style>
<form method="post" action="">
<textarea name="text"></textarea>
<br><input type="submit" name="btnTest" value="test">
</form>

<?php
if (isset($_POST['btnTest'])) {
$text = $_POST['text'];

$text = preg_replace("/[\r\n]+/", "\n", $text);
$text = preg_replace('#\*{2}(.*?)\*{2}#', "<br><br><span class='product-desc-section'>$1</span>", htmlspecialchars($text));
$text = preg_replace('~[\r\n]+~', "<br><span class='new-line'>&gt;&nbsp;</span>", $text);

echo "<pre>".$text."</pre>";
}
?>
</html>

Test-input:


**Title 1**
a
b
c

**Title 2**
x
y
z

Output:





Title 1


> a

> b

> c

>


Title 2

> x

> y

> z




Expected output:





Title 1


> a

> b

> c


Title 2

> x

> y

> z




How do I only place a >-icon on every new line which is not empty?



My Answer:
You can achieve this by using a negative lookahead in your regex pattern to exclude empty lines. Here's the updated code:

php
if (isset($_POST['btnTest'])) {
$text = $_POST['text'];

$text = preg_replace("/[\r\n]+/", "\n", $text);
$text = preg_replace('#\*{2}(.*?)\*{2}#', "

$1", htmlspecialchars($text));
$text = preg_replace('~\n(?!$)~', "
", $text);

echo "
".$text."
";
}


In the updated regex pattern `~\n(?!$)~`, `(?!$)` is a negative lookahead that asserts that the newline character is not followed by the end of the string. This way, only non-empty newlines will have the `>` icon placed before them.

Now, when you input the test data:

**Title 1**
a
b
c

**Title 2**
x
y
z

You should get the expected output:

Title 1
> a
> b
> c
Title 2
> x
> y
> z

Rate this post

3 of 5 based on 9721 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us