0

I am pretty new to PHP and hope someone here can help me with this:

I have a variable string that looks like the following, containing either nothing OR a series of words, separated with comma and space.

Example:

item1, item2, item3

What would be the best / fastest way to replace the single items in this string by adding an img tag with the same item name as the source + remove the commas ?

The above example should then look as follows:

item1 <img src="item1.png" alt="" /> item2 <img src="item2.png" alt="" /> item3 <img src="item3.png" alt="" />

Many thanks for any help with this, Mike.

2
  • 1
    A one-liner: echo implode("\n", array_map(function($v) {return '<img src="'.trim($v).'png" alt="" />'; }, explode(',', $str))); Commented Apr 26, 2014 at 18:38
  • 1
    echo preg_replace('/(\w+),?\s*/', '<img src="${1}.png" alt="" /> ', $str); Commented Apr 26, 2014 at 18:40

2 Answers 2

3

This can be done in a 1-liner, but since you're new to PHP, lets just make it clear.

First split the string to get an array of the different items.

$itemsStr = "item1, item2, item3";  // input string
$items = explode(", ", $itemsStr);  // Gets an array of items

Now traverse the items array and add the string for each item:

foreach($items as $key => $val)
{
    $items[$key] = $item . "<img src='$item.png' alt='' /> ";
}

$output = implode(" ", $items);
Sign up to request clarification or add additional context in comments.

1 Comment

nice one @Joshua Kissoon
1

This preg_replace should do it:

$in = 'item1, item2, item3';
$out = preg_replace('/( ?([^,]+)),?/', '$1 <img src="$2.png" alt="" />', $in);

$out then is:

item1 <img src="item1.png" alt="" /> item2 <img src="item2.png" alt="" /> item3 <img src="item3.png" alt="" />

1 Comment

Thanks for this. How would the number change here so that the img source is item1.png or item2.png or item3.png ?

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.