正则表达式和 str_replace,通过文本中 PHP 中的其他字符串修改字符串

RegEx and str_replace, modify a string by an other string in PHP from a text

我想通过 PHP 中的字符串从文本中转换一定数量的字符:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fringilla tincidunt justo sed hendrerit. Vivamus [im::17,I] elit id accumsan pulvinar. Fusce ac lacus arcu. Nullam imperdiet imperdiet eros, [im::31,R] congue libero. Aliquam non bibendum nisi. Nunc pretium feugiat nunc ut volutpat. Maecenas finibus viverra justo, quis luctus [im::11,L] facilisis vel.

所以我尝试做的是替换它:

[im::31,R]

由此:

<img src='img_31_0px.jpg' style='text-align:right;'/>

我得到了样式继承、左、右、中的数组,这不是我的难点。

这是我的实际功能:

function showimg($txtimg) {
        $fullstr = str_replace("[im::17,I]", "<img src='img_17_0px.jpg' style='text-align:inherit;'/>", $txtimg);
        return ($fullstr);
    }

如您所见,暂时是静态的,不是动态的。我正在寻找 http://www.regexr.com/ 尝试一些东西,但它并没有引导我到任何地方。

你们能帮我处理我的案子,或者至少引导我朝着好的方向发展吗? 谢谢。

我假设数字将是 1 位或 2 位数字。我让正则表达式捕获该标签并替换

中找到的数字
preg_replace('/\[im::(\d{1,2}),\w\]/', '<img src="img_\1_0px.jpg" style="text-align:inherit;"/>', $str);

https://3v4l.org/W0LuZ

这是我得到的结果:

function showimg($txtimg) {
        $fullstr = str_replace("[im::", "<img src='img_", $txtimg);
        $fullstr = str_replace(",I]", "_0px.jpg' style='max-width:100%; text-align:inherit;'/>", $fullstr);

        return ($fullstr);
    }

我终于用上了AbraCadaver

的答案

好吧,为了保持对齐,您需要回调:

function showimg($m) {
    $dir = array('I'=>'inherit','R'=>'right','L'=>'left');
    return '<img src="img_'.$m[1].'_0px.jpg" style="text-align:'.$dir[$m[2]].';"/>';
}

$result = preg_replace_callback('/\[im::([0-9]+),(I|R|L)\]/', 'showimg', $txtimg);