douxun4860 2010-03-03 03:17
浏览 58
已采纳

PHP正则表达式帮助 - 在另一个匹配中找到匹配并替换一些东西

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

  • 写回答

2条回答 默认 最新

  • dongye9820 2010-03-03 03:22
    关注

    Group the match and then use $matches[1] in the callback to only replace spaces in the part of the text between the quotes. 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了