Jump to content

[SOLVED] $text replace from array


StirCrazy

Recommended Posts

Hi folks,

 

I'm trying to sensor some text variables (but in a specific way).

 

 

Looks like this:-

 

$text = "text text text BOB1 text text text";

$replacetext = "*****";

 

$var1 = array("BOB","JACK","BILLY","HARVEY","JOHN");

$var2 = array("1","2","3","4","5");

 

 

If $text has "BOB" anywhere in the variable then check if it has a number from $var2 joined to it. If it has the replace "BOB1" with $replacetext.

 

 

 

Any ideas how to do this? Will love you forever if you can help.

 

S.C>

Link to comment
https://forums.phpfreaks.com/topic/57872-solved-text-replace-from-array/
Share on other sites

<?php
$text = "text BILLY3 text BOB1 text text JOHN1";
$replacetext = "*****";

$var1 = array("BOB","JACK","BILLY","HARVEY","JOHN");
$var2 = array("1","2","3","4","5");

// Couldn't you just use tihs array?
// $compArray = array("BOB1","JACK2","BILLY3","HARVEY4","JOHN5")

// if not, I'll build it.
$count = count($var1);
for($i = 0; $i < $count; ++$i){
$compArray[] = $var1[$i] . $var2[$i];
}

foreach($var1 as $token){
$text = str_replace($compArray, $replacetext, $text);
}

// Is this what you're looking for?
echo $text;
?> 

 

EDIT

 

I see you want any numbert in var 2... try this one:

 

<?php
$text = "text BILLY3 text BOB1 text text JOHN1";
$replacetext = "*****";

$var1 = array("BOB","JACK","BILLY","HARVEY","JOHN");
$var2 = array("1","2","3","4","5");

$count = count($var1);
for($i = 0; $i < $count; ++$i){
$count2 = count($var2);
for($c = 0; $c < $count2; ++$c){
	$compArray[] = $var1[$i] . $var2[$c];
}
}

foreach($var1 as $token){
$text = str_replace($compArray, $replacetext, $text);
}

echo $text;
?> 

 

Best,

 

Patrick

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.