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 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化