1

I want to replace different patterns in a string with the identical string. The replacements is an array with different values.

Since the pattern has to be mixed, I cannot find a solution. Also because preg_replace_all doesn't exist. Does anybody have an idea?

My code:

$artikelinhoud = $simpleXml->StandaardOplossing->attributes()->ArtikelInhoud;
$arrayImages = array();
preg_match_all('<!\[(CDATA)\[\s*(.*?)\s*\]\]>', $artikelinhoud, $arrayImages);

$images = array(); 
foreach ($arrayImages[2] as $key => $image) {
$images[$key] = 'src="data:image/jpg;base64,' . $image . '"';   
}

$imagesOld = array();
$imagesOld[] = '/type="(.*?)"/';

$artikelinhoud = preg_replace($imagesOld, $images , $artikelinhoud);

So variable $imagesold is always the same. And $images is an array with different values to put between tags.

5
  • preg_replace replaces already all occurances of the pattern. But propably you're interested in preg_replace_callback() Commented Nov 7, 2013 at 15:02
  • yes, but why it replaces all the patterns with $images[0] and not with $images[0], $images[1], etc? Commented Nov 7, 2013 at 15:06
  • Because with preg_replace() you're very limited in replacement of the matched string. But use preg_replace_callback() to have more possibillities. Commented Nov 7, 2013 at 15:07
  • 1
    I'd like to post the code, but I need to see an example of what $images looks like. Does it contain $1 that substitutes something for the capture group un $imagesOld? Commented Nov 7, 2013 at 15:14
  • images is array( [0]=> string(26464) "src="data:image/jpg;base64,/9j/4AA........) ,[1]=> string(22464) "src="data:image/jpg;base64,/9j/4AA........) it is meant to put between the <IGM> tag in HTML It needs to replace different times <IMG type="jpg"> So different images replace same patterns Commented Nov 7, 2013 at 15:17

1 Answer 1

1

I had a similar problem, I found this solution perfect for me.

In your code:

$artikelinhoud = $simpleXml->StandaardOplossing->attributes()->ArtikelInhoud;
$arrayImages = array();
preg_match_all('<!\[(CDATA)\[\s*(.*?)\s*\]\]>', $artikelinhoud, $arrayImages);

$images = array(); 
foreach ($arrayImages[2] as $key => $image) {
  $images[$key] = 'src="data:image/jpg;base64,' . $image . '"';   
}

$imagesOld = array_fill(0, count($images), '/type="(.*?)"/');

$artikelinhoud = preg_replace($imagesOld, $images , $artikelinhoud, 1);

Hope this helps.

Cheers!

Sign up to request clarification or add additional context in comments.

1 Comment

i already found a solution with DOM xpath, but thanks anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.