preg_replace正则表达式在行尾停止

问题描述 投票:0回答:2

坚持使用preg_replace选择和删除文本。我有一个起点Address:没有终点,但它确实以换行结尾。是否有正则表达式会使用换行符作为终点来删除文本行?

地址:大街123号城市:纽约

preg_replace('#Address:.*#si'), '', $lead_container)

以上删除了我希望保留的所有内容,包括城市:纽约。我可以使用City:作为终点,除非并非总是可用。首选将换行\n作为端点。

preg_replace('#Address:.*\n#si'), '', $lead_container)

尝试将\n\r添加到我的正则表达式中。仍然选择所有内容。如果有可能,我肯定会指出正确的方向。谢谢

php regex preg-replace
2个回答
1
投票

您有两种选择。首先,您可以删除正则表达式上的s选项;这将阻止.匹配换行符:

echo preg_replace('#Address:.*#i', '', $lead_container);

第二,您可以通过在?之后添加.*来使第二个示例中的正则表达式变为非贪婪:

echo preg_replace('#Address:.*?\n#si', '', $lead_container);

在两种情况下都输入]]

$lead_container = "Address: 123 Main Street
City: New York";

输出为City: New YorkDemo on 3v4l.org


0
投票

这在第一个空白

© www.soinside.com 2019 - 2024. All rights reserved.