【问题标题】:preg_replace for some characters in PHP [closed]preg_replace 用于 PHP 中的某些字符 [关闭]
【发布时间】:2013-09-13 05:55:30
【问题描述】:

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 之外的任何正则表达式测试器中尝试过它?
  • 使用 RegEx 教练亲自尝试一下,例如 weitz.de/regex-coach

标签: php regex preg-replace


【解决方案1】:

你的字符串:

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

preg_replace

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

str_replace

$arr = array(",", " ", "-", "__");
echo str_replace($arr, "_", $link);

【讨论】:

  • 简单的str_replace() 不是更适合这项任务吗?
  • 提问者想使用preg_replace
  • 我知道,但最好告诉他更好的方法;) RegExp 不适用于搜索/替换已知字符串。
  • @ElonThan 为你添加 ;) 顺便说一句,preg_replace 对我来说是个好主意 str_replace :)
  • 关于这个问题的讨论很好:)
【解决方案2】:

应该这样做:

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

【讨论】:

  • 这是正确的。 - 应该是 [] 中的最后一个字符,以避免将其与范围混淆。
【解决方案3】:

这是我想添加到 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

【讨论】:

    【解决方案4】:

    只是为了好玩,还有strtr

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

    【讨论】:

    • 为什么这被否决了?完全没问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2014-11-17
    • 1970-01-01
    相关资源
    最近更新 更多