用包含pattern的不同字符串替换字符串

Say you have a string like

$str = "<img src='i12'><img src='i105'><img src='i12'><img src='i24'><img src='i15'>....";

is it possible to replace every i+n by the nth value of an array called $arr so that for example <img src='i12'> is replaced by <img src='$arr[12]'>.

If I were you, I'd simply parse the markup, and process/alter it accordingly:

$dom = new DOMDocument;
$dom->loadHTML($str);//parse your markup string
$imgs = $dom->getElementsByTagName('img');//get all images
$cleanStr = '';//the result string
foreach($imgs as $img)
{
    $img->setAttribute(
        'src',
        //get value of src, chop of first char (i)
        //use that as index, optionally cast to int
        $array[substr($img->getAttribute('src'), 1)]
    );
    $cleanStr .= $dom->saveXML($img);//get string representation of node
}
echo $cleanStr;//echoes new markup

working demo here

Now in the demo, you'll see the src attributes are replaced with a string like $array[n], the code above will replace the values with the value of an array...

I would use preg_replace for this:

$pattern="/(src=)'\w(\d+)'/";
$replacement = '${1}\'\$arr[$2]\'';
preg_replace($pattern, $replacement, $str);

$pattern="/(src=)'\w(\d+)'/";

  • It matches blocks of text like src='letter + digits'.
  • This catches the src= and digit blocks to be able to print them back.

$replacement = '${1}\'\$arr[$2]\'';

  • This makes the replacement itself.

Test

php > $str = "<img src='i12'><img src='i105'><img src='i12'><img src='i24'><img src='i15'>....";
php > $pattern="/(src=)'\w(\d+)'/";
php > $replacement = '${1}\'\$arr[$2]\'';
php > echo preg_replace($pattern, $replacement, $str);
<img src='$arr[12]'><img src='$arr[105]'><img src='$arr[12]'><img src='$arr[24]'><img src='$arr[15]'>....