[英]PHP regex help - Find a Match Within Another Match and replace something
guys i have arrays in which i have to match this kind of text then remove spaces in-between the words , 伙计们,我有一些数组,在这些数组中我必须匹配这种文本,然后删除单词之间的空格,
Name:'lofse erbbnwq qweqw-qweqw' KKK
Name:'lofsdsse erbsdsdbnwq sds sdsd sdqwsdseqw-qwsdseqw' KKK
Name:'lofsse esdsdbnwq sds sds sddseqw-qwseqw' KKK
i read somewhere that it will work like this, but i tried and its not working :(
$data = preg_replace_callback('%Name:\'(.*)\' kkk%',replace_within_tag, $data);
function replace_within_tag($groups) {return preg_replace('/\s/', '.', $groups[0]);}
output should be like this 输出应该是这样的
Name:'lofse.erbbnwq.qweqw-qweqw' KKK
Name:'lofsdsse.erbsdsdbnwq.sds.sdsd.sdqwsdseqw-qwsdseqw' KKK
Name:'lofsse.esdsdbnwq.sds.sds.sddseqw-qwseqw' KKK
please i need some quick help on this, just tell me the working way 请我在这方面需要一些快速帮助,请告诉我工作方式
$array=array("Name:'lofse erbbnwq qweqw-qweqw' KKK", "Name:'lofsdsse erbsdsdbnwq sds sdsd sdqwsdseqw-qwsdseqw' KKK","Name:'lofsse esdsdbnwq sds sds sddseqw-qwseqw' KKK");
foreach ($array as $k=>$v){
if ( strpos($v,"Name:" ) !==FALSE) {
$s = explode("'",$v);
$s[1]=preg_replace("/\s+/",".",$s[1]);
$array[$k]=implode("'",$s);
}
}
print_r($array);
output 输出
$ php test.php
Array
(
[0] => Name:'lofse.erbbnwq.qweqw-qweqw' KKK
[1] => Name:'lofsdsse.erbsdsdbnwq.sds.sdsd.sdqwsdseqw-qwsdseqw' KKK
[2] => Name:'lofsse.esdsdbnwq.sds.sds.sddseqw-qwseqw' KKK
)
Group the match and then use $matches[1]
in the callback to only replace spaces in the part of the text between the quotes. 对匹配进行分组,然后在回调中使用
$matches[1]
仅在引号之间的文本部分替换空格。 You have a couple of ways of doing this. 您有两种方法可以做到这一点。 For example:
例如:
$output = preg_replace_callback("!(Name:')(.*?)(' KKK)!", 'replace_spaces', $input);
function replace_spaces($matches) {
return $matches[1] . preg_replace('!\s+!', '.', $matches[2]) . $matches[3];
}
You need to do this because you're capturing the leading and trailing strings. 您需要执行此操作,因为要捕获前导和尾随字符串。 An alternative way is to capture less.
另一种方法是少捕获。 For example:
例如:
$output = preg_replace_callback("!(?<=').*?(?=')!", 'replace_spaces', $input);
function replace_spaces($matches) {
return preg_replace('!\s+!', '.', $matches[0]);
}
This is using lookaheads and lookbehinds . 这使用了先行和后备 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.