【问题标题】:php find and replace a string within a stringphp在字符串中查找并替换字符串
【发布时间】:2014-02-27 03:22:48
【问题描述】:

我正在尝试扫描特定标签的字符串并将其替换为格式正确的 html。 例如,我想用

替换图像 id

到目前为止,我有这个扫描字符串并返回一个包含标签内 id 的数组

function get_image($string, $start, $end) {
    $start = preg_quote($start, '|');
    $end = preg_quote($end, '|');
    $matches = preg_match_all('|'.$start.'([^<]*)'.$end.'|i', $string, $output);
    return $matches > 0
        ? $output[1]
        : array();
} 

$output = get_image($string,'<img>','</img>');
for($x = 0; $x < count($output); $x++){
    $id = mysqli_real_escape_string($con,$output[$x]);
    $sql = "SELECT * FROM images WHERE image_id = '$id'";
    $query = mysqli_query($con,$sql);
    $result = mysqli_fetch_assoc($query);
    $replacement = '<img src="'.$result['img_src'].'" width="'.$result['img_width'].'" height="'.$result['img_height'].'" />';
}

$字符串示例

字符串示例是这样的一些文本
后跟一张图片
&lt;img&gt;1&lt;/img&gt;
还有一些文字

所以我现在有了这个 id 数组,可用于从数据库中获取图像 src 宽度高度。但不知道如何用新标签替换旧标签。

我可以使用 for 循环来格式化数组中的每个条目,但是如何将标签替换为字符串中正确位置的新格式化文本中的标签。

【问题讨论】:

  • 尝试 "/$start([^ 替换
  • 举例说明$string的值
  • 我添加了一个字符串的外观示例,它使用文本区域生成,文本编辑选项最少。它只是 我似乎无法弄清楚

标签: php html


【解决方案1】:

您可以使用preg_replace_callback()

// Get info of image $id
function getImageById($id){
    $sql = "SELECT * FROM images WHERE image_id = '$id'";
    return mysqli_query($con,$sql)->fetch_assoc();
}
// Proccess the info the regex gives and wants
function getImageById_regex($matches){
    // Some function to get the src by the id
    $img = getImageById( $matches[1] );
    return '<img src="'.$img['src'].'" alt="'.$img['alt'].'" />';

}
// The actual magic:
$string = preg_replace_callback("/<img>(.*?)<\/img>/", "getImageById_regex", $string);

在此版本中,getImageById() 返回一个包含信息的数组,但您可以更改它并使其返回整个图像 html。

可以改进:

// The actual magic, but first use a fast method to check if the slow regex is needed:
if( strpos($string, '<img>')!==false){
    $string = preg_replace_callback("/<img>(.*?)<\/img>/", "getImageById_regex", $string);
}

提示:四处寻找一些 BB 代码脚本。它们的工作方式相似

【讨论】:

  • 太好了,它确实正确格式化了字符串,但 mysqli 什么也不返回
  • $matches[0] 应改为 $matches[1]