PHP regex to limit new lines to a maxmium of two

杀马特。学长 韩版系。学妹 提交于 2019-12-11 06:48:41

问题


I'm using this but it's replacing single occurances of a new line with <br/><br/>

function nl2br2($string){
    $string = preg_replace('/(\r\n){2,}/', '<br/><br/>', $string);
    //$string = preg_replace('/[\r\n]/', '<br/>', $string);
    return $string;
}

It happens with the first pattern.


回答1:


Well, I suspect that perhaps your input may not be '/r/n' but only '\n'. In this case you should make your regex to detect that like this: '/(\r?\n){2,}/'.

So your code might be:

function nl2br2($string){
    $string = preg_replace('/(\r?\n){2,}/', '<br/><br/>', $string);
    return $string;
}

Hopes this helps.




回答2:


with the assistance of NawaMan i made my code this

function nl2br2($string){
    $string = preg_replace('/(\r?\n){2,}/', '<br/><br/>', $string);
    $string = preg_replace('/(\r?\n)+/', '<br/>', $string);
    return $string;
}

:) thanks



来源:https://stackoverflow.com/questions/1577535/php-regex-to-limit-new-lines-to-a-maxmium-of-two

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!