$text = "<p>Pellentesque ac urna eget diam volutpat suscipit
ac faucibus #8874# quam. Aliquam molestie hendrerit urna,
vel condimentum magna venenatis a.<br/> Donec a mattis ante.
Ut odio odio, ultrices ut faucibus vel, #2514# dapibus sed nunc. In hac sed.</p>";
I need to search for #myid# string, and replace with <a href='mylink.php?myid'>myid</a>
How can I do?
Why do you need regular expressions to do this, or are you planning to replace all 4 digit numbers (surrounded with #)??
If it's for a single ID, you could use:
$replace_id = 2514;
$replacement_find = "#{$replace_id}#";
$replacement_replace = "<a href=\"mylink.php?{$replace_id}\">{$replace_id}</a>";
$text_final = str_replace($replacement_find, $replacement_replace, $text);
If you're doing multiple replacements (or, as per comment, not knowing any IDs) you can use this:
$text_final = preg_replace('@#([0-9]+?)#@', '<a href="mylink.php?$1">$1</a>', $text);
EDIT: From your comment, you could use preg_match_all
to get all IDs in an array that are contained within the string. In the following code, $matches[1]
contains the value of everything within the ()
s in the regular expression, see return of print_r
.
preg_match_all('@#([0-9]+?)#@', $text, $matches);
print_r($matches[1]);
To accommodate your latest request, you can use preg_replace_callback
to get what you want:
function callback($matches) {
return '<a href="mylink.php?' . $matches[1] . '>' . getProductName($matches[1]) . '</a>';
}
$text_final = preg_replace_callback('@#([0-9]+?)#@', "callback", $text);
$text = preg_replace("/\#(\d+?)\#/s" , "<a href=\"mylink.php?$1\">$1</a>" , $text);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.