简体   繁体   中英

Regular expression for line breaks,new line & carriage returns

I want to replace "
,\\r,\\n" these characters & break tag from a string. I try to build following regular expression but failed.

$strText = preg_replace( '/[^\r|\n]|<br\W*?\/>/', ' ', $strText );

For eg:-

$strtext = 'Test111<br>222<br/>333\r444\n555';
Expected = 'Test111 222 333 444 555';

You can use the following solution:

$strText = 'Test111<br>222<br/>333\r444\n555';
$strText = preg_replace('/(<br\/*>|\\\r|\\\n)/', ' ', $strText);

var_dump($strText); //string(23) "Test111 222 333 444 555"

demo: https://ideone.com/xCqQsj

I would use an array

$strText = preg_replace( [
    "/[\r\n]/",    //New Lines
    "/<br[^>]*>/", //Break tags
    "/\s{2,}/"     //Run-on spaces
  ], " ", $strText );

When you use an array the replacements are done in order, so we can put \\s{2,} 2 or more spaces at the end to get any run-on spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM