Question

I want to make links using shortcuts following the pattern: controller/#/id. For example: a#3 must be rewritten to /actions/view/3, and t#28 must be a link to /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. 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?

Was it helpful?

Solution

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

OTHER TIPS

Since the number is not replaced you can use strtr (if it is not too ambigous) :

$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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top