2

I know there's a if/then in the matching of regular expressions, but is there one in the replace?

ie. I want to do in one regex

"I have Foo Bars under $5 for sale" to be "Foo Bars~$5"

"I have Foo Bars for sale" to become "Foo Bars" and NOT "Foo Bars~"

I have an expression a bit like this at the moment:

preg_replace("/(([A-Z][a-z]*\s){1,3})((under .)\d+)?/","$1~$4",$str);

(with other bits to remove the other text aswell of course!) but that includes the ~ even when there's no 'under' in it.

I could probably use preg_replace_callback but that seems a bit OTT

Thanks.

2
  • Why not compare the strings in php then have different preg_replace expressions for them? I don't understand the why you're searching for a complicated way to solve a simple solution. Commented Oct 19, 2010 at 16:05
  • Yes, in my example I could do that, but what I'm trying to do involves parsing a page of text and I'd quite like to get it done in one regexp if possible Commented Oct 20, 2010 at 7:28

1 Answer 1

2

Php's trim function would do:

// Before: "Foo Bars~$5"
    $str = trim($str,'~');
// After: "Foo Bars~$5"

// Before: "Foo Bars~"
$str = trim($str,'~');
// After: "Foo Bars"
Sign up to request clarification or add additional context in comments.

Comments

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.