[英]How to replace all occurrences of a character except the first one in PHP using a regular expression?
Given an address stored as a single string with newlines delimiting its components like:给定一个存储为单个字符串的地址,并用换行符分隔其组件,例如:
1 Street\nCity\nST\n12345
The goal would be to replace all newline characters except the first one with spaces in order to present it like:目标是用空格替换除第一个换行符以外的所有换行符,以便如下所示:
1 Street
City ST 12345
I have tried methods like:我试过这样的方法:
[$street, $rest] = explode("\n", $input, 2);
$output = "$street\n" . preg_replace('/\n+/', ' ', $rest);
I have been trying to achieve the same result using a one liner with a regular expression, but could not figure out how.我一直在尝试使用带有正则表达式的单行来实现相同的结果,但无法弄清楚如何。
You could use a regex trick here by reversing the string, and then replacing every occurrence of \n
provided that we can lookahead and find at least one other \n
:您可以在这里使用正则表达式技巧,通过反转字符串,然后替换每次出现的
\n
,前提是我们可以向前看并找到至少一个其他\n
:
$input = "1 Street\nCity\nST\n12345";
$output = strrev(preg_replace("/\n(?=.*\n)/", " ", strrev($input)));
echo $output;
This prints:这打印:
1 Street
City ST 12345
I would suggest not solving this with complicated regex but keeping it simple like below.我建议不要用复杂的正则表达式来解决这个问题,而是保持简单,如下所示。 You can split the string with a
\n
, pop out the first split and implode the rest with a space.您可以使用
\n
拆分字符串,弹出第一个拆分并用空格内爆 rest。
<?php
$input = explode("\n","1 Street\nCity\nST\n12345");
$input = array_shift($input) . PHP_EOL . implode(" ", $input);
echo $input;
You can use an alternation pattern that matches either the first two lines or a newline character, capture the first two lines without the trailing newline character, and replace the match with what's captured and a space:您可以使用匹配前两行或换行符的交替模式,捕获前两行而不使用尾随换行符,并将匹配替换为捕获的内容和空格:
preg_replace('/(^.*\n.*)\n|\n/', '$1 ', $input)
Demo: https://onlinephp.io/c/2fb2f演示: https://onlinephp.io/c/2fb2f
You can use a lookbehind pattern to ensure that the matching line is preceded with a newline character.您可以使用lookbehind 模式来确保匹配行前面有一个换行符。 Capture the line but not the trailing newline character and replace it with the same line but with a trailing space:
捕获该行但不捕获尾随换行符,并将其替换为同一行但尾随空格:
preg_replace('/(?<=\n)(.*)\n/', '$1 ', $input)
Demo: https://onlinephp.io/c/5bd6d演示: https://onlinephp.io/c/5bd6d
I leave you another method, the regex is correct as long as the conditions are met, in this way it always works我留给你另一种方法,只要满足条件,正则表达式就是正确的,这样它总是有效的
$string=explode("/","1 Street\nCity\nST\n12345");
$string[0]."<br>";
$string[1]." ".$string[2]." ".$string[3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.