PHP中的某些字符的preg_replace

时间:2013-09-13 05:55:30

标签: php regex preg-replace

如何在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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

这样的事情应该这样做:

<?php
    $subject = "http://test.com/test-one,two three";
    echo preg_replace ("/[, -]/" , "_", $subject);
?>

答案 2 :(得分: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

答案 3 :(得分:0)

只是为了好玩,还有strtr

strtr('http://test.com/test-one,two three', '-, ', '___');