douchuanhan8384 2019-04-09 06:41
浏览 6
已采纳

删除字符串中的所有单词“#User#,<br> <br>谢谢#在'#User#'和”#“之间提供”并从字符串中提取“#User#”

I need some regex that removes words as specified in title. I have tried below regex but it didn't worked. Also i want to extract "#User#" from given string - means starting with '#' and ending with '#' from string which don't contains any space.

preg_match_all("~#(.*?)#~", “#User#,<br><br>Thanks#For providing” , 
$wordReplaceArr_tmp);

Result of above code is below:

Output: User#,<br><br>Thanks

Expected result: "#User#"
  • 写回答

1条回答 默认 最新

  • dpa31905 2019-04-09 06:59
    关注

    If I got you right, you want the name(?) of the user between the first two hashtags and remove everything else. Your regex is greedy, means it captures more than it should. Add the hashtag to the "do not match" list and it will only capture anything UNTIL it finds another hashtag.

    $str = '#User#,<br><br>Thanks#For providing';
    preg_match_all('/#([^#]+)#/mis', $str, $matches);
    
    print_r($matches);
    

    The result of this code is the following:

    Array
    (
        [0] => Array
            (
                [0] => #User#
            )
    
        [1] => Array
            (
                [0] => User
            )
    
    )
    

    You can access the user now with $matches[1][0]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部