PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How can I append a string to a dynamic number value via preg_replace?

 November 20, 2022     php, preg-replace, regex, string     No comments   

Issue

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

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.



Answered By - Kacper
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing