Page 1 of 1

[SOLVED] preg_replace from URL

Posted: Wed Oct 20, 2004 12:24 am
by zolee1
Hi,

I am fairly new to PHP.
I would like to crate FROM $url = "http://www.a1-whatever-4u.com/";
this string: A1-whatever-4u.com
The code bellow produces A1-whatever-4u.com/.
I can't get rid of the '/' at the end.
Also I would like to make sure that if
I have a URL starting with a digit that I wouldn't get an error.
With the current code I might get, because it would try to capitalize the first character after the www.

Code: Select all

<?php
$url = "http://www.a1-whatever-4u.com/";

$replacement = "strtoupper('\$4').'\$5'";
echo preg_replace("/(http:)(\/\/)(www.)([a-zA-Z0-9])([a-zA-Z0-9])+([\/])?/e", 
             $replacement, 
             $url);
?>

Any suggestions would be appreciated.

Zolee

Posted: Wed Oct 20, 2004 12:47 am
by feyd
you're very close..

Code: Select all

<?php

	$url = "http://www.a1-whatever-4u.com/";
	
	$replacement = "strtoupper('\\\\2').'\\\\3'";
	echo preg_replace("#http://(www\.)?([a-z0-9])([a-z0-9_\.-]+)(/.*)?$#ieS", 
		$replacement, 
		$url);

?>

Posted: Wed Oct 20, 2004 8:09 am
by zolee1
Thanks feyd,

But I get the same result as with my code:
A1-whatever-4u.com/

Do you know how can I loose the / at the end, so I would get only this:

A1-whatever-4u.com

Thanks,
Zolee

Posted: Wed Oct 20, 2004 8:45 am
by feyd
mine works correctly. Consider switching to preg_match.. your original pattern doesn't match the entire string.

Posted: Wed Oct 20, 2004 8:49 am
by zolee1
Hi Feyd,

Maybe I did something wrong, but it didn't work. I modified your code:

Code: Select all

<?php

$url = "http://www.a1-whatever-4u.com/";

echo preg_replace("#http://(www\.)?([a-z0-9])([a-z0-9_\.-]+)(/.*)?$#ieS", 
             "strtoupper('\$2').'\$3'",
             $url);

?>
and it works now!!!

Thank You!!!

Do you know any good place on the net where I can find explanation of the syntax of regular expressions.

I know the basic stuff, but I don't know what that means at the end in your code : #ieS

Thanks Again!

Zolee

Posted: Wed Oct 20, 2004 8:52 am
by feyd

Posted: Wed Oct 20, 2004 9:10 am
by zolee1
Thanks again!

It was very helpful.

Zolee

Posted: Wed Oct 20, 2004 10:11 am
by The Monkey
Amazing, I log on to ask this very question, and what do I get? The code already laid out for me! w00tsies.