php在字符串中查找并替换字符串
我正在尝试扫描字符串中的特定标记,并用格式正确的html替换它们。 例如,我想用 到目前为止,我已经有了这个方法,它扫描字符串并返回一个数组,其中包含标记中的idphp在字符串中查找并替换字符串,php,html,Php,Html,我正在尝试扫描字符串中的特定标记,并用格式正确的html替换它们。 例如,我想用 到目前为止,我已经有了这个方法,它扫描字符串并返回一个数组,其中包含标记中的id function get_image($string, $start, $end) { $start = preg_quote($start, '|'); $end = preg_quote($end, '|'); $matches = preg_match_all('|'.$start.'([^<]*)
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'].'" />';
}
函数get_image($string,$start,$end){
$start=preg_quote($start,“|”);
$end=preg_quote($end,“|”);
$matches=preg_match_all(“|”。$start.”([^您可以通过以下方式使用类似的内容:
小贴士:四处寻找一些BB代码脚本。它们的工作原理类似Try/$start([^举例说明$string的值我已经添加了一个示例说明该字符串的外观,它是使用文本编辑选项最少的文本区域生成的。只是我似乎无法理解这很好它确实正确设置了字符串的格式,但mysqli不返回任何内容$matches[0]应该更改为$matches[1]
// 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);
// 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);
}