0

I have got multidimensional array (name + image path), where some names are similar, like:

array("name" => "OpenGL", "img" => "OpenGL.png"),
array("name" => "OpenGL Lighting ( Advanced )", "img" => "OpenGL-LightingAdvanced.png")

then I replace names with images.

foreach ($extensions as $extension) {
    $ret=str_ireplace($extension['name'],'<img src="images/'.$extension['img'].'" alt="'.$extension['name'].'" />: ',$ret);
}

It works as long as array is sorted from shortest name to longest one, but in that case, longer names will never be changed, eg. OpenGL Lighting ( Advanced ) will be

<img src="images/OpenGL.png" alt="OpenGL" /></div>:  Lighting ( Advanced )

When I sort it from longes name to shortest one it is even worse, couse it will change name in src:

<img src="images/<img src="images/OpenGL.png" alt="OpenGL" />: -LightingAdvanced.png" alt="<img src="images/OpenGL.png" alt="OpenGL" />:  Lighting ( Advanced )" />: 

My only idea is to check if there isn't src="images/ or alt=" before name, if so - replace, but I have no idea how can I easily do.

2
  • You could always just add the quotes to the replace, delimiting it! Commented May 11, 2013 at 21:30
  • Something like str_ireplace($extension['name']." "? Sadly I can't do so :( Commented May 11, 2013 at 21:37

3 Answers 3

1

Maybe sprintf will work:

foreach ( $extensions as $extension ) {
    $ret = sprintf( '<img src="images/%s" alt="%s" />: ', htmlspecialchars( $extension['img'] ), htmlspecialchars( $extension['name'] ) );
}
Sign up to request clarification or add additional context in comments.

3 Comments

You'll need htmlspecialchars() for the string arguments to ensure correct html output...
100% true, post updated to htmlspecialchars( $extension['img'] )
Maybe nooby, but I don't see how I can quickly use sprintf. $ret contains string like "bla bla OpenGL bla bla OpenGL Lighting ( Advanced ) bla" and I want to change that names into images...
0

You don't need the foreach loop around str_ireplace(), just use it like this:

$ret=str_ireplace($array_of_all_search_words, $array_of_all_replacement_words, $ret);

and it won't replace anything it has already replaced. You might still have to sort the search words by length, though.

Comments

0

Somebody mentioned strtr().

Very helpful but case-sensetive and I need case-insensitive function.
Luckily somebody wrote case-insensitive function stritr() in the comments.

Comments

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.