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 很弱
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 很弱
你的字符串:
$link = 'http://test.com/test-one,two three';
echo preg_replace('/[\s,-]+/', '_', $link);
$arr = array(",", " ", "-", "__");
echo str_replace($arr, "_", $link);
这样的事情应该这样做:
<?php
$subject = "http://test.com/test-one,two three";
echo preg_replace ("/[, -]/" , "_", $subject);
?>
这是我想添加到 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
只是为了好玩,还有strtr
:
strtr('http://test.com/test-one,two three', '-, ', '___');