Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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:用正则表达式模拟爆炸_Php_Regex - Fatal编程技术网

PHP:用正则表达式模拟爆炸

PHP:用正则表达式模拟爆炸,php,regex,Php,Regex,我想用正则表达式模拟explode函数。 例如:给定字符串:“/home/index/6” 我希望能够从以下字符串获取数组:[“home”、“index”、“6”] 不使用函数爆炸 我尝试过以下代码: <?php $regex = "(/|(/([a-zA-Z]+))+)"; $url = $_GET["url"]; if(preg_match("@" . $regex . "@", $url, $matches)) { echo "<pre>"; pri

我想用正则表达式模拟explode函数。 例如:给定字符串:“/home/index/6” 我希望能够从以下字符串获取数组:[“home”、“index”、“6”] 不使用函数爆炸

我尝试过以下代码:

<?php

$regex = "(/|(/([a-zA-Z]+))+)";

$url = $_GET["url"];

if(preg_match("@" . $regex . "@", $url, $matches)) {
    echo "<pre>";
    print_r($matches);
    echo "</pre>";
}
您需要使用函数来执行全局正则表达式匹配

Array
(
    [0] => Array
        (
            [0] => home
            [1] => index
            [2] => 6
        )
)

您可以这样做,但要获得多个结果,您需要使用
preg\u match\u all
。在不使用
preg\u split
的情况下模拟爆炸的最佳方法可能是使用
\G
锚定,以确保所有匹配都是连续的:

([^\/]+)
要明确的是,除了使用
explode
之外,没有什么好处,这是最快的方法,我假设您希望将此作为一种练习

您可以尝试此操作。使用
搜索
而不是
匹配
。请参阅演示


为什么不使用explode()?为什么使用??而不是在\A/??@walidtoumi中:当字符串以前导斜杠开头时,目标是获得一个空结果(与explode一样)。在这种情况下,
量词强制不匹配斜杠,并匹配斜杠前的空字符串。@walidtoumi:但它没有用,因为简单的
\a
也会这样做。我将编辑我的答案。事实上,没有。我正在构建一个MVC框架(主要用于我自己的网站),我希望用户能够为路由提供正则表达式。非常感谢您的帮助,顺便说一句:)这是一个目录路径。所以它必须以/symbol开头。这个
[^\/]*(?=\/$)
就可以了。
$regex = '~(?:\A|\G/)\K[^/]*~';

if (preg_match_all($regex, $url, $matches)) { 
    print_r($matches[0]);
([^\/]+)