Link to home
Start Free TrialLog in
Avatar of Gagik
Gagik

asked on

PHP String operations

Hi I need a PHP function that will located these tags {} and replace them with some content.

http://www.google.com?myvar1={id1}&myvar2={id2}&myvar1={id3}&myvar2={id4}

For instance myvar2={id2} must be replaced with myvar2=$my_row('id2') etc...

So it must locate {} and grab whatever is in between (i.e. id2) and use it with mysql.

Here's what the final result must look like:

http://www.google.com?myvar1=123&myvar2=456&myvar1=789&myvar2=474

thanks
Avatar of subscript
subscript

What about using str_replace function:

Example:

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

From:
http://us2.php.net/manual/en/function.str-replace.php

Does that work for you?
Avatar of Gagik

ASKER

it will not work right away because I never know what asre these tags.
i first must make a search in order to make alist of all existing tags, i.e. {id1}, {id2}, {id3}... and then I will be able to replace it.
id1, id2, id3 ... they all correspond to a field in MySQL table. after having located these tags I will replace these parts of the string with $row['id1'], $row['id2'], $row['id3']...

So the first step is to find a way of making a list of these tags. I must refer to these brackets {}
ASKER CERTIFIED SOLUTION
Avatar of subscript
subscript

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gagik

ASKER

I created my own 2 functions. I'm going to try your code too though because it looks simpler. Here's mine:


	private function getQueryStringTags($str){
		
		$qsTags = array();
		
		$beg=0;
		$end=0;
	
		//print '<br />'.$str.'<br />';
		
		while( $beg < strlen($str) ){
			
			$beg = strpos($str, '{', $beg);		
			
			$end = strpos($str, '}', $end+1);		
			
			array_push($qsTags, substr($str, $beg+1, $end-$beg-1) );
			
			$beg = $end+1;
			
		}
		
		//print_r($qsTags).'<br />';
		
		return $qsTags;		
	}
	
	private function replaceTags( $str, $row, $qsTags ){
		
		foreach( $qsTags as $key => $val ){
			
			$str = str_replace('{'.$val.'}', $row[$val], $str);			
		
		}
		
		return $str;		
	}

Open in new window

Any luck?