php preg_replace删除最后一个新行字符?

时间:2017-03-30 13:20:47

标签: php preg-replace

我的数据库中有以下字符串,我想删除" \ r \ n"在字符串的末尾,我尝试了多次,但都失败了

例如,见下文

<?php

$text = 'Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue\r\n';

echo $essay = preg_replace("/(\\r\\n)$/", ' ', $text);
echo preg_replace("/\=\r\n$/", " ", $text);

我正在用

进行测试

http://phptester.net/

但无法获得预期的输出

$text = 'Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue';

2 个答案:

答案 0 :(得分:1)

要删除的\r\n不是CR + LF符号,而是4个字符串,因为在单引号字符串文字中,\是文字反斜杠。因此,您的字符串以\r\n结尾。要将文字\与正则表达式匹配,您需要使用4个反斜杠,而不是2个。

请参阅PHP demo

$text = 'Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue\r\n';
echo $essay = preg_replace("/\\\\r\\\\n$/", '', $text);

请注意,您可以检查字符串是以\r\n结尾,然后是substr

答案 1 :(得分:1)

首先,您需要将单个'更改为dobule引用字符串"

$text = "Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue\r\n";

然后使用

echo $essay  = preg_replace('/\\r+\\n/', '', $text);
相关问题