RegEx Help

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

RegEx Help

Post by aliasxneo »

Code: Select all

$sql = preg_replace("/\'(\d)\'/", "$1", $sql);
I'm trying to replace integers that have single quotes around them with the original integer. All you need to focus on here is the regular expression:

Code: Select all

/\'(\d)\'/
The problem is that it only replaces one digit integers, and not anything bigger then that. How do I make it so that it accepts any length of integer?

E.G The above expression works for:

'1'

But not for

'10'

Because there's two digits and I only specified one. Thanks.

Cheers,
- Josh
georgeoc
Forum Contributor
Posts: 166
Joined: Wed Aug 09, 2006 4:21 pm
Location: London, UK

Post by georgeoc »

After a character you can add a * symbol to mean "any number", or a + symbol to mean "at least 1". You can also do {3} to mean "exactly 3" or {2, 6} to mean "between 2 and 6".

So, to answer your question, try this:

Code: Select all

$sql = preg_replace("/\'(\d+)\'/", "$1", $sql);
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

In regex you say [what to match][how many to match].
What to match can be anything you like.
How many can be:

* - 0 or more
+ - 1 or more (probably what you want)
{2,5} - between 2 and five

Btw you are escaping your single quotes when you don't need to.

Edit: Damn beaten to it :(
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Come now.. there's a board named "regex."
aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

Post by aliasxneo »

Thanks for the help, got it working. Cheers.
Post Reply