[英]PHP - Regular Expression to Remove Single Quotes From Beginning and End of a String
[英]PHP: how to remove by regular expression from a precise characther to the end of the string
我有下面这样的数组:
Array("string|||mfasdfhadskjfahsldfhcadkasldhfaf", "apple|||2345hrquwfiqfh4fhlqwu4f", "orange|||0erjoerhtqothcro")
我想要实现的是:
Array("string", "apple", "orange")
我可以使用什么正则表达式删除“ |||”之后的所有字符?
亲切的问候,马西
在简单的情况下,使用strstr
函数就足够了:
$arr = ["string|||mfasdfhadskjfahsldfhcadkasldhfaf", "apple|||2345hrquwfiqfh4fhlqwu4f", "orange|||0erjoerhtqothcro"];
$result = array_map(function ($s) {
return strstr($s, '|||', true);
}, $arr);
print_r($result);
输出:
Array
(
[0] => string
[1] => apple
[2] => orange
)
将array_map
与简单的preg_replace
调用结合使用。
您只需要在第一个|
之后替换所有内容即可|
用''
。
$data = ...
$data = array_map(function($item) {
return preg_replace('~\|.*$~', '', $item);
}, $data);
如果您需要3倍的管道字符,只需使用\\|{3}.*$
这里有两种方法,我建议第二种,因为它不使用正则表达式。
但是,关于preg_replace()
是您不需要编写循环。
代码:( 演示 )
$array = ["string|||mfasdfhadskjfahsldfhcadkasldhfaf", "apple|||2345hrquwfiqfh4fhlqwu4f", "orange|||0erjoerhtqothcro"];
var_export(preg_replace('~\|.*~', '', $array));
echo "\n----\n";
foreach ($array as &$value) { // modify by reference to overwrite the input array
$value = strstr($value, '|', true);
}
var_export($array);
输出:
array (
0 => 'string',
1 => 'apple',
2 => 'orange',
)
----
array (
0 => 'string',
1 => 'apple',
2 => 'orange',
)
或strstr()
无需通过引用进行修改,则可以声明一个新的结果数组,如下所示:
foreach ($array as $value) {
$result[] = strstr($value, '|', true);
}
ps当然,如果您的真实数据需要三个连续的管道,则可以再延长两次我的指针字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.