我试图使用preg_match_all()
函数在_
之后搜索字符串。我想要的输出将是reset,text,email
。我试图使用regexr编辑器并使其能够与[_]+[a-z]*
合作,但这将包括_reset, _text, _text
。该字符串将是:在下划线之前或之后提取子字符串
$str = 'button_reset,location_text,email_text';
预期输出:
reset
text
email
我试图使用preg_match_all()
函数在_
之后搜索字符串。我想要的输出将是reset,text,email
。我试图使用regexr编辑器并使其能够与[_]+[a-z]*
合作,但这将包括_reset, _text, _text
。该字符串将是:在下划线之前或之后提取子字符串
$str = 'button_reset,location_text,email_text';
预期输出:
reset
text
email
这将是更好地避免正则表达式这任务,只是使用str_replace()
:
输入:
$str = 'button_reset,location_text,email_text';
代码为阵列输出:
var_export(explode(',',str_replace(['button_reset','location_text','email_text'],['reset','text','email'],$str)));
// array (
// 0 => 'reset',
// 1 => 'text',
// 2 => 'email',
//)
或者,如果你坚持,正则表达式(Demo Link):
/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/
正则表达式击穿:
button_\K[^,]+ #Match one or more non-comma-characters after button_
| #or
,location_\K[^,]+ #Match one or more non-comma-characters after location_
| #or
,\K[^_]+(?=_text) #Match one or more non-underscore-characters that are
# immediately followed by _textafter button_
在每个条件表达式的\K
装置从该点匹配和有效地除去使用捕获组进行这种情况下的需要。 当使用捕获组时,preg_match_all()
创建了多个子数组 - 一个填充了全部字符串匹配,并且至少还有一个捕获值。应尽可能使用 \K
,因为它可以将阵列大小减少50%。
代码:
$array=preg_match_all('/button_\K[^,]+|,location_\K[^,]+|,\K[^_]+(?=_text)/',$str,$out)?$out[0]:[];
var_export($array);
的输出结果相同:
array (0 => 'reset', 1 => 'text', 2 => 'email',)
我想使用preg_match() –
这次不是明智的选择。我可以制作一个,但它不是这项任务的正确功能。给我一点时间。 – mickmackusa
正则表达式:/\_\K[a-zA-Z0-9]+
\_\K
这将匹配_
和\K
将全部重置比赛。2.
[a-zA-Z0-9]+
会匹配所有这些字符
<?php
ini_set('display_errors', 1);
$str = 'button_reset,location_text,email_text';
preg_match_all("/\_\K[a-zA-Z0-9]+/",$str,$matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => reset
[1] => text
[2] => text
)
)
你期望的输出是没有意义的。 “email”不在下划线之后。 –