开发者

How do I create regex groups for replacement?

开发者 https://www.devze.com 2023-02-03 19:00 出处:网络
I have this sample string: Image:SGD$45.32 SKU: 3f3f3 dfdfd grg4t BP 6yhf Pack Size: 1000\'s Color: Green Price: SGD$45.32 SGD$45...

I have this sample string:

Image:  SGD$45.32 SKU: 3f3f3 dfdfd grg4t BP 6yhf Pack Size: 1000's Color: Green Price: SGD$45.32 SGD$45...

I would like to remove all the prices namely:

SGD$45.32  
Price: SGD$45.32  
SGD$45  

I have this expression thats supposed to match the 3 groups:

$pattern = '/(Price.+\sSGD\$\d+\.\d{2})(SGD\$\d+\.\d{2})(SGD\$\d+)/';  
$new_snippet = preg_replace($pattern, '', $snippet); 

But apparently its not working.

It works if I replace a single group at a time. But, I'd like to know if it possible to replace all possible matching groups with a single statement.

Tried preg_match_all($pattern, $snippet, $match开发者_JS百科es); to show matches based on the above pattern, but no matches are found if I put all 3 groups together.


try this:

$output = preg_replace(array('/Price: /s', '/SGD\$.+? /s'), '', $input);


To answer your specific question: use | to conditionally group them:

$pattern = '/(Price.+\sSGD\$\d+\.\d{2})|(SGD\$\d+\.\d{2})|(SGD\$\d+)/';  

This replaces a substring if it matches any of:

  • (Price.+\sSGD\$\d+\.\d{2})
  • (SGD\$\d+\.\d{2})
  • (SGD\$\d+)

I would rewrite the entire regex into this though:

$pattern = '/(?:Price.+\s*)?SGD\$\d+(?:\.\d{2})?/';  

This would replace occurrences of Price: SGD$45 as well.


Did you try separating them with |'s?

0

精彩评论

暂无评论...
验证码 换一张
取 消