'How can I append a string to a dynamic number value via preg_replace?

I have a string inside another to which I need to append something.

The structure of string is something like this:

$output = "Family: peppers, dimensions: 150 cm, origin: South America, Pot diameter: 14, height with pot: 80";

In that string I need to find Pot diameter and append to its numeric value the string cm. so it will look like

Pot diameter: 14 cm.

In the site it appears like this:

Family: peppers.
Dimensions: 150cm
Origin: South America
Pot diameter: 14
Height with pot: 80

I have been trying to use preg_replace() via

$output = preg_replace("/Pot diameter: [0-9]+/", '\0 cm.', $output)

but it doesn't work at all. I can't figure out how to find a number within given string - an exact number won't work because it's used dynamically. Only letters inside this string are static.

I figure out that Source code shows:

<div><br/>
<b>Średnica doniczki: </b>
14<br/>
</div>

Changing to:

$output = preg_replace("/<b>Średnica doniczki: </b> <br/>[0-9]+/", '\0 cm.', $output);

Dosen't work either.

I have now solution

$output = preg_replace("/<b>Średnica doniczki: <\/b>(.*?)<\/div>/", 'Średnica doniczki: $1 cm.</div>', $output);

I just picked the next closing tag, and find anything between given string and ending tag, and then just inject the same string with first taken value and it works as i wanted to do.



Solution 1:[1]

I solved my problem via

$output = preg_replace("/<b>?rednica doniczki: <\/b>(.*?)<\/div>/", '?rednica doniczki: $1 cm.</div>', $output);

To do so I just picked the next closing tag,
In the next step I find anything between given string and ending tag,
Next I just inject the same string what is given with first taken value and closing tag
And now it works as i wanted to do.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kacper