简体   繁体   English

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

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

I want to make links using shortcuts following the pattern: controller/#/id. 我想使用模式后面的快捷方式建立链接:controller /#/ id。 For example: a#3 must be rewritten to /actions/view/3, and t#28 must be a link to /tasks/view/28. 例如:#3必须重写为/ actions / view / 3,而t#28必须是/ tasks / view / 28的链接。 I think preg_replace is an "easy" way to achieve this, but I'm not that good with regular expressions and I don't know how to "reuse" the digits from the search-string within the result. 我认为preg_replace是一种“简单”的方法来实现这一点,但我对正则表达式并不是那么好,我不知道如何在结果中“重用”搜索字符串中的数字。 I think I need something like this: 我想我需要这样的东西:

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

Can someone point me in the right direction? 有人能指出我正确的方向吗?

You can "reuse" the numbers from the search strings using capturing groups , denoted by brackets () . 您可以使用捕获组 “重用”搜索字符串中的数字,用方括号()表示。
Try this - 尝试这个 -

$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)
**/

The above answer works, but if you need to add more of those search values, you can store those keys in separate array and you can use preg_replace_callback . 上面的答案有效,但是如果你需要添加更多的搜索值,你可以将这些键存储在单独的数组中,你可以使用preg_replace_callback
This also does the same thing, but now, you only need to add more (alphabets)keys in the array and it will replace it accordingly. 这也做同样的事情,但是现在,你只需要在数组中添加更多(字母)键,它就会相应地替换它。
Try something like this- 试试这样的事情 -

$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)
**/

Since the number is not replaced you can use strtr (if it is not too ambigous) : 由于数字未被替换,您可以使用strtr(如果它不太暧昧):

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

if you can use this, it will be faster than processing a string two times with a regex. 如果你可以使用它,它将比使用正则表达式处理字符串两次更快。

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

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