如何在字符串中查找图像标记并找到图像标记的src并替换为包含新src的数组。
array(
[0] => YogurtParfait.png
[1] => Smoothie_0.png
[2] => Waffle.png
[3] => EggSandwich_0.png
[4] => BlueberryMuffins.png
)
这是我想用字符串src替换的数组。
$string = 'This is my test <img src="link_to_image1">, some other text
<img src="link_to_image1">
<img src="link_to_imag">
<img src="link_to_im">
<img src="link_to_imag">.
我希望得到像这样的出局
$string = 'This is my test
<img src="YogurtParfait.png">,
some other text<img src="Smoothie_0.png">
<img src="Waffle.png">
<img src="EggSandwich_0.png">
<img src="BlueberryMuffins.png">.
答案 0 :(得分:0)
如果所有<img>
标记确实具有相同的src
属性,您可以迭代执行:
$links = array("YogurtParfait.png", ...);
$string = "This is my ...";
foreach ($links as $link) {
$string = str_replace("link_to_image1", $link, $string);
}
如果它们实际上是link_to_image1
,link_to_image2
......那么:
$links = array("YogurtParfait.png", ...);
$string = "This is my ...";
foreach ($links as $k => $link) {
$string = str_replace("link_to_image$k", $link, $string);
}
<强>更新强>
事实证明src
是动态的,所以:
$links = array("YogurtParfait.png", ...);
$string = "This is my ...";
$startpos = strpos($string, '<img'); // position of first occurrence of <img
foreach ($links as $link) {
$string =
substr($string, 0, $startpos) // the part before the <img part
. preg_replace(
'/(<img src=")[^"]+(">)/',
'\1' . $link . '\2',
// the part from the actual <img part
substr($string, $startpos)
);
// get position of next <img part
$startpos = strpos($string, '<img', $startpos + 1);
}
答案 1 :(得分:0)
让$array1
成为包含数组的变量的名称。然后:
$array2 = array();
foreach($array1 as $i=>$src)
$array['link_to_image' . ($i + 1)] = $src;
$output = strtr($string, $array2);