编程语言
首页 > 编程语言> > PHP,Regex仅在两个保留的字符之间替换用户输入中的换行符

PHP,Regex仅在两个保留的字符之间替换用户输入中的换行符

作者:互联网

我正在处理textarea用户输入,其中保留了一些字符,例如:

[ means <h1>
] means </h1>
{ means <p>
} means </p>

用户输入示例:

[Hello World title]
{hello worlds paragraph
and paragraph continues after line break}

系统显示示例:

<h1>Hello World title<h1>
<p>hello worlds paragraph<br/>
and paragraph continues after line break</p>

所有HTML标记都从用户输入中过滤掉,PHP脚本将这些字符替换为前端.

我想使用PHP函数“ nl2br”用< br />替换换行符.

问题是只有{和}字符之间的换行符应替换为< br />.

另外,我还需要考虑用户是否使用{}输入了多个段落.

解决方法:

我将使用preg_replace_callback同时进行两个替换:

<?php

$input="{user input
user input}

newlines that aren't replaced";

function format_paragraph($m){
    return '<p>'.nl2br($m[1]).'</p>';
}

echo preg_replace_callback("/\{(.*)\}/s",format_paragraph,$input);

?>

测试代码here

此示例将添加p标记,并在一个替换中替换换行符.

标签:preg-replace,php,regex
来源: https://codeday.me/bug/20191201/2078541.html