繁体   English   中英

PHP:正则表达式替换字符串中的#3

[英]PHP: regex to replace a#3 in string

我想使用模式后面的快捷方式建立链接:controller /#/ id。 例如:#3必须重写为/ actions / view / 3,而t#28必须是/ tasks / view / 28的链接。 我认为preg_replace是一种“简单”的方法来实现这一点,但我对正则表达式并不是那么好,我不知道如何在结果中“重用”搜索字符串中的数字。 我想我需要这样的东西:

$search = array('/a#\d/', '/t#\d/');
$replace = array('/actions/view/$1', '/tasks/view/$1');
$text = preg_replace($search, $replace, $text);

有人能指出我正确的方向吗?

您可以使用捕获组 “重用”搜索字符串中的数字,用方括号()表示。
尝试这个 -

$text = "a#2 a#3 a#5 a#2 t#34 t#34 t#33 t#36";
$search = array('/\ba#(\d+)\b/', '/\bt#(\d+)\b/');
$replace = array('/actions/view/$1', '/tasks/view/$1');
$text = preg_replace($search, $replace, $text);
var_dump($text);
/**
OUTPUT-
string '/actions/view/2 /actions/view/3 /actions/view/5 /actions/view/2 /tasks/view/34 /tasks/view/34 /tasks/view/33 /tasks/view/36' (length=123)
**/

上面的答案有效,但是如果你需要添加更多的搜索值,你可以将这些键存储在单独的数组中,你可以使用preg_replace_callback
这也做同样的事情,但是现在,你只需要在数组中添加更多(字母)键,它就会相应地替换它。
试试这样的事情 -

$arr = Array(
    "a"=>   "/actions/view/",
    "t"=>   "/tasks/view/"
);
$text = preg_replace_callback("/\b([a-z]+)#(\d+)\b/", function($matches) use($arr){
    var_dump($matches);
    return $arr[$matches[1]].$matches[2];
},$text);
var_dump($text);
/**
OUTPUT-
string '/actions/view/2 /actions/view/3 /actions/view/5 /actions/view/2 /tasks/view/34 /tasks/view/34 /tasks/view/33 /tasks/view/36' (length=123)
**/

由于数字未被替换,您可以使用strtr(如果它不太暧昧):

$trans = array('a#' => '/actions/view/', 't#' => '/tasks/view/');
$text = strtr($text, $trans);

如果你可以使用它,它将比使用正则表达式处理字符串两次更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM