Php 在下划线之前或之后提取子字符串
我尝试使用Php 在下划线之前或之后提取子字符串,php,regex,string,substring,preg-match-all,Php,Regex,String,Substring,Preg Match All,我尝试使用preg\u match\u all()函数来搜索\u后面的字符串。我想要的输出将是重置、文本、电子邮件。我尝试使用编辑器创建它,并能够使用[\u]+[a-z]*创建它,但这将包括\u重置、\u文本、\u文本。字符串将是: $str = 'button_reset,location_text,email_text'; 预期输出: reset text email Array ( [0] => Array ( [0] =>
preg\u match\u all()
函数来搜索\u
后面的字符串。我想要的输出将是重置、文本、电子邮件。我尝试使用编辑器创建它,并能够使用[\u]+[a-z]*
创建它,但这将包括\u重置、\u文本、\u文本
。字符串将是:
$str = 'button_reset,location_text,email_text';
预期输出:
reset
text
email
Array
(
[0] => Array
(
[0] => reset
[1] => text
[2] => text
)
)
正则表达式:
/\\uk[a-zA-Z0-9]+
1.\\uk
这将匹配\\ucode>,而\K
将重置整个匹配
2.[a-zA-Z0-9]+
将匹配所有这些字符
正则表达式:/\\uk[a-zA-Z0-9]+
1.\\uk
这将匹配\\ucode>,而\K
将重置整个匹配
2.[a-zA-Z0-9]+
将匹配所有这些字符
对于此任务,最好避免使用正则表达式,只需使用str\u 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',
// )
或者如果您坚持,Regex():
正则表达式细分:
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\u match\u all()
会创建多个子数组——一个子数组填充了fullstring匹配,至少还有一个子数组填充了捕获的值。
应尽可能使用\K
,因为它可以将数组大小最多减少50%
代码:
相同输出:
array ( 0 => 'reset', 1 => 'text', 2 => 'email', )
对于此任务,最好避免使用正则表达式,只需使用str\u 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',
// )
或者如果您坚持,Regex():
正则表达式细分:
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\u match\u all()
会创建多个子数组——一个子数组填充了fullstring匹配,至少还有一个子数组填充了捕获的值。
应尽可能使用\K
,因为它可以将数组大小最多减少50%
代码:
相同输出:
array ( 0 => 'reset', 1 => 'text', 2 => 'email', )
我想使用preg_match()这一次不是明智的选择。我可以做一个,但它不是这个任务的正确功能。给我一分钟。我想使用preg_match()这一次不是明智的选择。我可以做一个,但它不是这个任务的正确功能。给我一分钟,你期望的结果没有意义。“电子邮件”不在下划线之后。您的预期输出没有意义。“email”不在下划线后面。