[Solved]preg_replace confusion

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
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

[Solved]preg_replace confusion

Post by Steveo31 »

Hey all. I'm learning the preg_*, and after going through php.net's manual about 10 times I'm having some problems with this one here:

Code: Select all

preg_match("/^(http:\/\/)?([^\/]+)/i","http://www.php.net/index.html",$matches);
I know how it is translating up to the "?[^\/]+" part. What is this part saying? What is it negating?

Also, the "?" is confusing me as it has more than one meaning. One is "to extend the meaning of", and the other being "a 0 or 1 quantifier".

Cound you clear this up for me? :)
Last edited by Steveo31 on Tue Mar 30, 2004 3:15 pm, edited 1 time in total.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

The [^\/]+ says to look for any character except a forward slash. The ? mark indicates that there can be 0 or 1 instances of 'http://' to start the string.

Mac
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Post by Steveo31 »

That makes some sense. But why the backslash in there first? I guess it hase to be escaped...

The ? stll gets me though. In this case I understand, but I don't see why it would be used instead of * or +.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

? would be used instead of + or * because you want to make sure that there is 0 or 1, not any number - you don't want to match something like http://http://http://www.site.com.

The backslash escapes the forward slash because the forward slash is being used as the pattern delimiter - you could probably change the whole thing to:

Code: Select all

!^(http://)?(ї^/]+)!i
Mac
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Post by Steveo31 »

Perfect. Thanks Mac.
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post by tim »

http://www.zend.com/zend/tut/tutorial-delin2.php

if you havent read that reg ex tut, tis the one I thought I advanced most with.

=]
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Post by Steveo31 »

tim wrote:http://www.zend.com/zend/tut/tutorial-delin2.php

if you havent read that reg ex tut, tis the one I thought I advanced most with.

=]
Ah nice one. Agreed :)
Post Reply