-1

I'm trying to write a function that will replace any occurrence of numbers that start and ends with PID. I think the problem is in the regex but I can't figure it out. The code is below. I also tried just (.) instead of (.*) - no difference. I know I will have to loop through the matches array to get all occurrences but I wanted to get the basic code working first. Would someone please point out the problem?

    function DoLinks($matches) {
     return ($matches[0]='<a href="someplace.com">Some place</a>');
    } 

    function Buildinks($text) {
      preg_replace_callback(
         "/PID(.*)PID/",
         "DoLinks",
         $text);
      return $text;
    }

    $text = "hello PID(199)PID";
    $text = Buildinks($text);
    echo $text;
user3052443
  • 758
  • 1
  • 7
  • 22

1 Answers1

0

The function preg_replace_callback returns a value, which you can return in the Buildinks function.

And the $matches[0]= can be removed in DoLinks.

The regex now has a lazy match .*?.
Just in case you got text with more than 1 PID.

<?php
function DoLinks($matches) {
    $pid = $matches[1];
    return '<a href="someplace.com">Some place with pid '.$pid.'</a>';
} 

function Buildinks($text) {
    return preg_replace_callback('/PID\((.*?)\)PID/', 'DoLinks', $text);
}

$text = "hello PID(199)PID and hello PID(200)PID";
$text = Buildinks($text);
echo $text;
LukStorms
  • 28,916
  • 5
  • 31
  • 45