php 的简码 preg_replace

问题描述 投票:0回答:1

我正在学习语言

php
。我有两个函数,我想连接这两个函数并在一个输出中显示它们
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);
?>

输出(html);

it is a test. Link: -

但我想显示输出(

html
)如下:

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

它应该显示此代码

<a href="follow/link/44">Follow : 44</a>
。 我认为这段代码
preg_replace
不起作用。

php preg-replace
1个回答
0
投票

因为您传递给函数的字符串

'$1'
没有特殊含义,所以您应该使用
preg_replace_callback
函数:

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

function link_follow($matches)
{
    $id = $matches[1];
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.