【问题标题】:PHP Split String on Forward Slash Only If It Is Not Preceded By A Backslash仅当前面没有反斜杠时,PHP 在正斜杠上拆分字符串
【发布时间】:2013-11-14 22:10:09
【问题描述】:

我正在为我的SlashCategory 制作解析器,这需要我根据/ 字符拆分(或标记化)每个字符串。我正在使用 PHP 的 explode() 函数,效果很好。例如,它需要以下内容:

Book/Title/Lord Of The Flies/Author/William Golding

并创建一个数组:

[0] Book
[1] Title
[2] Lord Of The Flies
[3] Author
[4] William Golding

但是,我有一个问题。如果正斜杠前面有反斜杠,我不希望 explode() 分解字符串。例如:

Url/Google/http:\/\/www.google.com

我想要一个包含以下内容的数组:

[0] Url
[1] Google
[2] http://www.google.com

不是:

[0] Url
[1] Google
[2] http:
[3] 
[4] www.google.com

我该怎么做?

【问题讨论】:

  • 我会用什么语法告诉它忽略\/
  • 使用负面的后视
  • 好的。所以我有preg_split("((?<!\\\)/)", $line)。但是当我使用something/http:\/\/test之类的东西时,它会返回http:\/\/test

标签: php string parsing explode


【解决方案1】:

使用preg_split(请参阅http://php.net/manual/en/function.preg-split.php)。示例:

$input = 'Url/Google/http:\/\/www.google.com';
$output = preg_split('|(?<!\\\)/|', $input); //Yes, thats 3 times a backslash

现在,$output 中的数据仍将包含您转义的斜杠,您需要取消转义它们,如下所示:

$output = preg_split('|(?<!\\\)/|', $input);
array_walk(
    $output,
    function(&$item){
        $item = str_replace('\\/', '/', $item);
    }
);

【讨论】:

  • 谢谢!这帮助很大。
【解决方案2】:

哈,我知道这有其缺点,但一个班轮可能是这样的:

<?php
    $s = "Url/Google/http:\/\/www.google.com";
    var_dump (explode('#####',str_replace('\\#####','/',str_replace('/','#####',$s))));
?>

虽然你必须找到一个除了 '#####' 之外的实用的东西,因为你可能有一个可以解析的字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多