shortcode preg_replace by php

70 Views Asked by At

I am learning the language php. I have two functions and I want to connect these two and show them in one output php.

<?php
function link_follow($id)
{
    $title = '';
    $slug = '';
    if ( $id == 44 ){
        $title = 'Follow';
        $slug = 'link/'.$id;
        $read = '<a href="follow/'. $slug .'">'. $title .' : '.$id.'</a>';
        return $read;
    }
    return '-';
}

function content_html($string)
{
    $string = preg_replace('/\[FOLLOW_LINK id=(\d+)\]/i',  link_follow('$1') , $string);
    return $string;
}

$content= 'it is a test. Link: [FOLLOW_LINK id=44]';
echo content_html($content);
?>

out (html);

it is a test. Link: -

But i want to show the output (html) as below:

it is a test. Link: <a href="follow/link/44">Follow : 44</a>

It should show this code <a href="follow/link/44">Follow : 44</a>. I think this code preg_replace does not work.

2

There are 2 best solutions below

0
shingo On BEST ANSWER

Because the string '$1' you passed to the function has no special meaning, you should use the preg_replace_callback function:

preg_replace_callback('/\[FOLLOW_LINK id=(\d+)\]/i', 'link_follow', $string);

function link_follow($matches)
{
    $id = $matches[1];
    ...
}
0
Pippo On
$string = preg_replace('/\[FOLLOW_LINK id=(\d+)\]/i',  link_follow('$1') , $string)

doesn't work because link_follow('$1') is executed before the replacement and since link_follow('$1') will return '-', also the replace() will result in '-'.

Also if you pass '$1' instead of link_follow('$1') as the second parameter, the substitution will result as the original string with the search pattern changed to the value that $1 represents ('it is a test. Link: 44' in the example).

A possible alternative solution is to use preg_match() which accepts as third parameter an array where the matches are stored, $matches[0] will contain the $0 match and $matches[1] will contain your $1 match:

function content_html($string)
{
    $matches = [];
    preg_match('/\[FOLLOW_LINK id=(\d+)\]/i', $string, $matches);
    
    return link_follow($matches[1] ?? '');
}