Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.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/1/amazon-web-services/12.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 如何使用preg_replace替换斜杠中的所有内容?(仅每隔一个匹配项被替换)_Php_Url_Preg Replace - Fatal编程技术网

Php 如何使用preg_replace替换斜杠中的所有内容?(仅每隔一个匹配项被替换)

Php 如何使用preg_replace替换斜杠中的所有内容?(仅每隔一个匹配项被替换),php,url,preg-replace,Php,Url,Preg Replace,我不熟悉正则表达式,我一直试图将它与url一起使用,但我无法让它工作 我有一个字符串: /插件/插件/插件/插件/插件/插件/插件/ 我想替换字符串“{char}”中的所有字母,以便字符串最终为: /{char}/{char}/{char}/{char}/{char}/{char}/ 我试过这个: <?php $pattern = '#(/)([a-z\_]+)(/)#'; $replacement = '$1{char}$3'; $stri

我不熟悉正则表达式,我一直试图将它与url一起使用,但我无法让它工作

我有一个字符串:

/插件/插件/插件/插件/插件/插件/插件/

我想替换字符串“{char}”中的所有字母,以便字符串最终为:

/{char}/{char}/{char}/{char}/{char}/{char}/

我试过这个:

<?php
    $pattern        = '#(/)([a-z\_]+)(/)#'; 
    $replacement    = '$1{char}$3'; 
    $string         = '/plugins/plugins/plugins/plugins/plugins/plugins/';

    echo preg_replace($pattern, $replacement, $string);
?>

但该代码导致了以下情况:

/{char}/plugins/{char}/plugins/{char}/plugins/


我做错了什么?

问题是您的正则表达式匹配的是
/plugins/
-前后都匹配斜杠。每个字母只由正则表达式匹配一次,因此,如果一个斜杠在一个单词的末尾匹配,那么它也不能算作另一个单词的开头。因此,它只匹配其他每一个

请尝试以下方法:

<?php
    $pattern        = '#(/)([a-z\_]+)(?=/)#'; 
    $replacement    = '$1{char}'; 
    $string         = '/plugins/plugins/plugins/plugins/plugins/plugins/';

    echo preg_replace($pattern, $replacement, $string);
?>


它的工作原理是使用,而不是实际匹配最终斜杠(并“使用”它),它只是检查以确保它在那里

我要添加的所有内容,您已经编辑到您的答案中。除了指出由于在本例中,
$1
始终是
/
,您可以删除括号,在替换字符串中只包含一个文本
/