get strings from string

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
pedroz
Forum Commoner
Posts: 99
Joined: Thu Nov 03, 2005 6:21 am

get strings from string

Post by pedroz »

$string="google=12 yahoo=publish bing='ok' ask=0";

how get the following from the $string?...
echo $google; output 12
echo $yahoo; output plublish
echo $bing; output 'ok'
echo $ask; output 0
buckit
Forum Contributor
Posts: 169
Joined: Fri Jan 01, 2010 10:21 am

Re: get strings from string

Post by buckit »

This works:

Code: Select all

<?php
$string="google=12 yahoo=publish bing='ok' ask=0";

$string=explode(' ',$string);
foreach($string as $v){
	$exp = explode('=',$v);
	$resultArray[$exp[0]] = $exp[1];
}

echo $resultArray['google'];
echo $resultArray['yahoo'];
echo $resultArray['bing'];
echo $resultArray['ask'];
?>
First we explode $string into an array using a space as the separator... that then puts 'google=12' as a value in the array. next we loop through that array and explode each value using = as the separator. then we put the first value as the key in a new array and the second value as the new arrays value for that key.
Post Reply