字符串处理 - PHP字符替换问题

WBOY
Release: 2016-06-06 20:21:33
Original
1153 people have browsed it

直接上代码吧

<code>$str = '\Handler\TestHandler.php';
$need = ['\\', '\\'];
$new_need = [0,1];
$result = str_replace($need, $new_need, $str);
//$result=>0Handler0TestHandler.php</code>
Copy after login
Copy after login

结果不应该是0Handler1TestHandler.php吗?

是哪里出问题了吗?

回复内容:

直接上代码吧

<code>$str = '\Handler\TestHandler.php';
$need = ['\\', '\\'];
$new_need = [0,1];
$result = str_replace($need, $new_need, $str);
//$result=>0Handler0TestHandler.php</code>
Copy after login
Copy after login

结果不应该是0Handler1TestHandler.php吗?

是哪里出问题了吗?

你的两个\全都被0给替换了,语法详情

php应没有内置的这种方法,需要自己写一个函数,下面这个应该可以实现你的功能

<code>
function replace ($str) {
    $i = 0;
    $result = '';
    $arr = explode("\\", $str);
    foreach ($arr as $val) {
        if ($val === '') continue;
        $result .= ($i++).$val;
    }
    return $result;
}
</code>
Copy after login

因为是数组替换是先后替换啊,第一个替换已经把两个 \ 替换成了 0,后面那个替换就匹配不到 \ 了,自然没有 1 了。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template