duancong6937 2015-09-30 12:48
浏览 23
已采纳

用于删除开始和结束引用之间的空格的正则表达式(PHP)

I would like to remove spaces if they are shown on start or end of a name inside qotes. Let me explain more on example:

This is the result i have:
" HAIRDRESSER PERSON 1" Person one businesses
" HAIR STUDIO " Person two S.P.
" HAIRDRESSER PERSON 3     " - PERSON 3 S.P.

And this is what i'm trying to achieve:
"HAIRDRESSER PERSON 1" Person one businesses
"HAIR STUDIO" Person two S.P.
"HAIRDRESSER PERSON 3" - PERSON 3 S.P.

This is the code i'm working on:

$data[$num]['title'] = preg_replace(????????, "",$row->find('td',1)->plaintext);

If you have any better solution then preg_replace i'm open for it. Thank you guys in advance.

  • 写回答

5条回答 默认 最新

  • dousu1900 2015-09-30 13:01
    关注

    It isn't safe to only search quoted text that need to be trimmed (for example: "abcd" efgh " ijkl " can be problematic with this approach and a naive pattern).

    A possible way consists to search all quoted parts and to trim them using preg_replace_callback:

    $data[$num]['title'] = preg_replace_callback('~"([^"]*)"~', function ($m) {
        return '"' . trim($m[1]) . '"'; }, $row->find('td', 1)->plaintext);
    

    The advantage of this way is that the pattern used is very simple.

    You can also avoid preg_replace_callback but you need a more complicated pattern:

    $data[$num]['title'] = preg_replace('~"\s*+([^\s"]*(?:\s+[^\s"]+)*+)\s*"~', '"$1"', $row->find('td', 1)->plaintext);
    

    Note that these two patterns assume that quotes are balanced and that quoted parts don't contain escaped quotes.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么