looking for RexExp pattern

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

looking for RexExp pattern

Post by vigge89 »

I'm looking for a Regular Expression pattern which looks something like:

Code: Select all

\ї(ї0-9]{1})\](.*?)\ї/(ї0-9]{1})\]
It should match the following ({$int} means an number between 1-6:

Code: Select all

ї{$int}]some textї/{$int}]
Both the start and the ending $int should be the same number.

That's the problem, previously i've always used patterns which replaced the $int with the numbers from 1 to 6, resulting in 6 patterns. I though I'd ask here if anyone knows how to make the start and ending $int required to be the same, or the pattern shouldn't match. The things which should be passed on is the $int and the text, but if the last $int also is passed, it won't matter.

Thanks in advance, I hope you understood ;)
hokiecsgrad
Forum Newbie
Posts: 17
Joined: Fri Oct 22, 2004 2:55 pm

Post by hokiecsgrad »

You need to use backreferencing. Using your example:

$someText = "1some text1";
$someOtherText = "1some text5";

echo $preg_match( "/^(\d)(.)*\1$/", $someText );
echo $preg_match( "/^(\d)(.)*\1$/", $someOtherText );

You should find that you get a match with the first string but not the second. The \1 is the backreference here. That reg ex is just saying "Find an integer in the beginning of the string and store it in position 1, then look for any character or characters and then find what was stored in position 1 at the end of the string."
hokiecsgrad
Forum Newbie
Posts: 17
Joined: Fri Oct 22, 2004 2:55 pm

Post by hokiecsgrad »

I should also mention that in my example above, I create a second backreference that you could access using "\2" in my regular expression. The backreference is created by the parenthesis.

If that's not clear, do some searches looking for regular expressions and back references.
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post by vigge89 »

thanks, i think i got it to workd now, final code:

Code: Select all

$patterns[] = "#\[([0-9]{1}?)\](.*?)\[/\\1\]#si";
	$replacements[] = "<h\\1>\\2</h\\1>";
Post Reply