-3

php中如何使用preg_replace()将逗号、空格、连字符替换为下划线。

(i.e) http://test.com/test-one,two three  to http://test.com/test_one_two_three

(i.e) http://test.com/test, new one  to http://test.com/test_new_one

我的 reg_exp 很弱

4

4 回答 4

2

你的字符串:

$link = 'http://test.com/test-one,two three';

preg_replace

echo preg_replace('/[\s,-]+/', '_', $link);

str_replace

$arr = array(",", " ", "-", "__");
echo str_replace($arr, "_", $link);
于 2013-09-13T06:00:54.950 回答
2

这样的事情应该这样做:

<?php
    $subject = "http://test.com/test-one,two three";
    echo preg_replace ("/[, -]/" , "_", $subject);
?>
于 2013-09-13T06:02:25.760 回答
1

这是我想添加到 PHP 中的功能的预览:

function url_replace($url, $component, callable $callback)
{
    $map = [
        PHP_URL_SCHEME => 2,
        PHP_URL_HOST => 4,
        PHP_URL_PATH => 5,
        PHP_URL_QUERY => 7,
        PHP_URL_FRAGMENT => 9,
    ];

    if (!array_key_exists($component, $map)) {
        return $url;
    }
    $index = $map[$component];

    if (preg_match('~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~', $url, $matches, PREG_OFFSET_CAPTURE) && isset($matches[$index])) {
        $tmp = call_user_func($callback, $matches[$index][0]);
        return substr_replace($url, $tmp, $matches[$index][1], strlen($matches[$index][0]));
    }
    return $url;
}

回答你的问题变成:

$url = 'http://test.com/test-one,two three';
echo url_replace($url, PHP_URL_PATH, function($path) {
    return strtr($path, ', -', '___');
});

结果:

http://test.com/test_one_two_three
于 2013-09-13T06:59:08.333 回答
0

只是为了好玩,还有strtr

strtr('http://test.com/test-one,two three', '-, ', '___');
于 2013-09-13T06:33:46.933 回答