John Davidson

php - I'm trying to remove extra lines between the texts using preg_replace but it is not working as expected

0 comments
Message:


I'm trying to remove extra lines between the texts and here is what I tried:


<?php
echo preg_replace("/^\s+/", "\n", $_POST["description"]);

The input:



The output:



I tried the same regular expression on regex101 and here is the result:



As you can see nothing changed when I executed the regular expression using PHP, But it is working as what I want when using the regex101 website.


The current PHP version is 7.4.28.


Did I miss something?



My Answer:
It looks like you are using the wrong regular expression pattern in your preg_replace function. The pattern "/^\s+/" is used to match one or more whitespace characters at the beginning of a line, but it does not remove extra lines between the texts.

To remove extra lines between the texts, you can use the following regular expression pattern:

php
echo preg_replace("/\n{2,}/", "\n", $_POST["description"]);


This pattern matches two or more consecutive newline characters and replaces them with a single newline character, effectively removing the extra lines between the texts.

Try using this pattern in your preg_replace function and see if it gives you the desired output.

Rate this post

5 of 5 based on 4958 votes

Comments




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