Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 匹配和删除字符串中的twitter哈希标记_Php_Regex_Preg Replace - Fatal编程技术网

Php 匹配和删除字符串中的twitter哈希标记

Php 匹配和删除字符串中的twitter哈希标记,php,regex,preg-replace,Php,Regex,Preg Replace,只有当hashtag位于字符串末尾以外的任何位置时,我才需要从hashtags中删除#字符。示例: 这个月我要去迪斯尼#WDW 这个月我要去迪斯尼#奥兰多 这个月我要去奥兰多的迪斯尼乐园 它们需要转换为: 这个月我要去迪斯尼 这个月我要去迪斯尼 这个月我要去迪斯尼 此代码将删除所有#字符: function remove_hashtags($string){ $result = preg_replace('/#([\w-]+)/i', '$1', $string); return

只有当hashtag位于字符串末尾以外的任何位置时,我才需要从hashtags中删除#字符。示例:

这个月我要去迪斯尼#WDW

这个月我要去迪斯尼#奥兰多

这个月我要去奥兰多的迪斯尼乐园

它们需要转换为:

这个月我要去迪斯尼

这个月我要去迪斯尼

这个月我要去迪斯尼

此代码将删除所有#字符:

function remove_hashtags($string){
    $result = preg_replace('/#([\w-]+)/i', '$1', $string);
    return $result;
}
…但在此之前,需要删除字符串末尾的hashtag(或一组hashtag)。

这如何

function remove_hashtags($string){
    return str_replace('#', '', 
        preg_replace('/(?:#[\w-]+\s*)+$/', '', $string));
}
我假设您只需要删除所有“#”字符,而不仅仅是后跟“hashtag标识符候选者”(匹配
[\w-]+
模式)的字符

如果这是您的任务,则应相应调整代码:

function remove_hashtags($string){
    return preg_replace('/#(?=[\w-]+)/', '', 
        preg_replace('/(?:#[\w-]+\s*)+$/', '', $string));
}

我在这里用前瞻取代了捕获组。另外,在这两种情况下都不需要<代码> /i < /代码>修饰符:<代码> \W特殊字符涵盖了<代码> -AZ和<代码> -Z 范围。

请仔细考虑使用将被删除的实体I和Y 039的字符串;m此操作还删除诸如';