TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Basic Loop with [ str_replace] (http://www.talkphp.com/absolute-beginners/4930-basic-loop-str_replace.html)

hello-world 09-05-2009 01:37 PM

Basic Loop with [ str_replace]
 
I have a problem with replacing and looping.I need your help please to change
This line
Quote:

The quick brown {fox} jumps over the lazy {dog}
To this
Quote:

The quick brown cat jumps over the lazy mouse.
PHP Code:

$string 'The quick brown {fox} jumps over the lazy {dog}';
$arr = array("fox" =>"Cat","dog"=>"mouse");
preg_match_all("/{.*?}/",$testing,$matches); 

By the way how to practice looping in php ?
Is there any good exercise for it ?

Wildhoney 09-05-2009 05:08 PM

You don't necessarily need a loop to achieve this. You could do the following:

php Code:
$szItem   = 'The quick brown {fox} jumps over the lazy {dog}';
$aReplaceThese  = array('fox', 'dog');
$aReplaceWidth  = array('cat', 'mouse');

$szItem         = str_replace($aReplaceThese, $aReplaceWidth, $szItem);
echo $szItem;

Although, if you wish to practice loops, then I could show you how to achieve it with a foreach loop.

tony 09-05-2009 05:25 PM

or you can also use the translate function:
php Code:
<?php
$string = 'The quick brown {fox} jumps over the lazy {dog}';
$arr = array("{fox}" => "cat","{dog}" => "mouse");
echo 'before: ' . $string . "\n";
$string = strtr($string, $arr);
echo 'after: ' . $string;
?>

hello-world 09-06-2009 06:31 PM

Thanks alot WildHoney and Tony.:-)


All times are GMT. The time now is 08:03 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0