doulu1867
2014-12-16 08:20
浏览 35
已采纳

php正则表达式字符串替换

I have a string like that as json response for a script:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, HTTP://unknown/string/in/unknown/place/ , sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"

is there a way to replace with an empty string using regular expression and php preg_replace?

I'm not familiar with regular expression, could you just provide an example? I basically need to remove the substring starting with 'http' and finishing with a space, IF possible.

thanks

图片转代码服务由CSDN问答提供 功能建议

我有一个像这样的字符串作为脚本的json响应:

  “Lorem ipsum dolor sit amet,consectetur adipiscing elit,HTTP:// unknown / string / in / unknown / place /,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua”
   
 
 

有没有办法用正则表达式和php preg_replace用空字符串替换

我不熟悉常规 表达,你能提供一个例子吗? 我基本上需要删除以'http'开头并以空格结束的子字符串,如果可能的话。

谢谢

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drhqkz3455 2014-12-16 08:25
    已采纳

    Something like

    preg_replace("/HTTP\S+\s,/", "","Lorem ipsum dolor sit amet, consectetur adipiscing elit, HTTP://unknown/string/in/unknown/place/ , sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" );
    

    Will give output as

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
    

    Regex /HTTP\S+\s,/

    • \S matches anything other than a space

    • \s matches a space

    Regex Demo

    EDIT

    A better solution like

    /HTTP\S+(\s,|$)/
    

    So that the link can apear anywhere in the string even at the end.

    Example

    preg_replace("/HTTP\S+(\s,|$)/", "","Lorem ipsum dolor sit amet, consectetur adipiscing elit, HTTP://unknown/string/in/unknown/place/" );
    => Lorem ipsum dolor sit amet, consectetur adipiscing elit,
    

    Regex Demo

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题