I'm wondering a good way of splitting strings by a |
delimiter if the input strings could be of the following form:
"foo, bar"
"foo ,bar"
"foo,bar"
"foo , bar"
"foo bar"
"foo,,bar"
So the only possible outputs strings are as:
"foo|bar"
"foo|bar|other|here"
Independently of how many terms are within the input string.
Any thoughts would be appreciated!
preg_replace('/\s*,\s*/', '|', $string);
这将以逗号处理;)如果您也需要仅包含空格的情况:
preg_replace('\s*,\s*|\s+', '|', $string);
我会做:
$input = preg_replace('/[ ,]+/', '|', $input);
Something like this should do the trick...
$outputstring = preg_replace_all('/\b[ ,|]+\b/','|',$inputstring);
to explain:
\\b
is a word-boundary, so it is looking for any combination of spaces, commas or pipes between two word boundaries.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.