string manuplation

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
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

string manuplation

Post by itsmani1 »

in below mentioned strings i want to remove everything after .html

xxxxxxx.html?xxx=xxxx
xxxxxxx.html?xxx=xxxx&xxx=xxxxxx

how can i do this?
i don't want to hard code it.
User avatar
Jaxolotl
Forum Contributor
Posts: 137
Joined: Mon Nov 13, 2006 4:19 am
Location: Argentina and Italy

combine two functions

Post by Jaxolotl »

with this "stupid" but fast script you may do that

Code: Select all

$string = "xxxxxxx.html?xxx=xxxx&xxx=xxxxxx.html.html";

/*
the function first check if you feed it with a string containing characters
if not it returns an error message
then, if it finds ".html" on the string
replace all the content from the fist match to the end with ".html"
if not match it returns the string as is
*/


function my_replacement($my_string){
	if($my_string){
		$limit = @strpos($my_string, ".html",0);
		if($limit){
			return substr_replace($my_string, ".html",$limit);
		}
		else{
			return $my_string;
		}
	}
	else{
		return "no string has been given";
	}
}
echo my_replacement($string);
note that it stops at the first match of ".html"

you may inprove it by using switch inside instead of it so if no argument was givent to the functions you wont go on error

http://it2.php.net/manual/en/function.strpos.php
http://it2.php.net/manual/en/function.s ... eplace.php
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

http://www.php.net/manual/en/function.preg-replace.php

Code: Select all

$var=preg_replace('/(.+html\?).*/iu',"${1}",$orig_string");
or something similar...
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

Maybe a quicker way of doing it:

Code: Select all

$str = "asdf.html?xxx=xxxx&xxx=xxxx";
$str_chopped = substr($str, 0, strpos($str, '?'));
Post Reply