如何查找子字符串,然后用PHP正则表达式替换子字符串


How can I find and then replace a substring with PHP regexp?

我有一个表达式,正是这样:{库id='2'}

我想从这个表达式中获得id(在本例中为2),而不是将完整的标记替换为另一个字符串。

更具体地说,我想做以下事情:

内容中的字符串:

{gallery id='2'}

使用preg_replace_callback(),我想调用这个函数:

function changeNumberToGalleryName( $id ){
    //get name of the gallery from database where ID = $id
    ....
    ....
    return $galleryname;
}

我想将{gallery id='2'}替换为gallery的名称

谢谢你的建议!

preg_replace("/{'s?'w+'s?id's?='s?''d+''s?}/", $gallername, $text);

如果你不想修改你的函数,你可以这样做:

$str = preg_replace_callback('~{gallery id='''K'd+~',
                             function ($match) {
                                 return changeNumberToGalleryName($match[0]);
                             },
                             $str);

但如果你可以修改它(即用$id[0]替换他体内所有出现的$id),你可以写:

$str = preg_replace_callback('~{gallery id='''K'd+~',
                             'ChangeNumberToGalleryName',
                             $str);

但你真的需要一个函数来做到这一点吗?如果图库名称位于关联(或索引)数组中,例如:

array(
"1" => "gallery 1 name"
"2" => "gallery 2 etc.
)
or
array('nop', 'gallery 1 name', 'gallery 2 name' ...)

 nbsp 你只需要使用匿名功能:

$str = preg_replace_callback('~{gallery id='''K'd+~',
                             function ($match) { return myarray[$match[0]]; },
                             $str);

匹配完整标签并捕获标识符:

$re = "/{gallery id='([^']+)'}/";
preg_replace_callback($re, function($match) {
    return changeNumberToGalleryName($match[1]);
}, $string);

表达式([^']+)匹配任何东西,直到找到撇号为止,并将找到的字符串捕获到匹配的第一存储器位置中;稍后我将使用$match[1]传递该值。

我在这里使用回调来通过内存捕获提取标识符,然后将其传递给您的函数;这样你就不必修改你的函数。