문제

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, $matches); 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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top