multiple string replace - php

I need to replace multiple text with it's associated text
Example: I have string like: "apple is a great fruit"
Now I need to replace "apple" to "stackoverflow", and "fruit" to "website"
I know I can use str_replace, but is there any other way? str_replace would be slow in my case, because I need to replace atleast 5 to 6 words
Help appreciated.

<?php
$a = array('cheese','milk');
$b = array('old cow','udder');
$str = 'I like cheese and milk';
echo str_replace($a,$b,$str); // echos "I like old cow and udder"
Alternatively, if you don't like to look of that (worried of miss matching array values) then you could do:
$start = $replace = $array();
$str = "I like old cow and udder"
$start[] = 'cheese';
$replace[] = 'old cow';
$start[] = 'milk';
$replace[] = 'udder';
echo str_replace($start,$replace,$str); // echos "I like old cow and udder"
edit: I see dnl has edited the question and put emphasis on the fact that str_replace would be too slow. In my interpretation of the question it is because the user was not aware that they would use arrays in str_replace.

if u know all the word sequence and also replaced word then use below technique
$trans = array( "apple" => "stackoverflow", "fruit" => "website");
echo strtr("apple is a great fruit", $trans); // stackoverflow is a great website
Reference

For your purpose str_replace seams to be already the fastest solution.
str_replace is faster than strstr
Source: http://www.simplemachines.org/community/index.php?topic=175031.0

Related

Stop replacing text in string after first replacement in PHP

Here is an example:
$original_string = 'I like apples very much. I want an apple.';
$temp_string = str_replace('apples', '_apples_', $original_string);
// $temp_string is now: I like _apples_ very much. I want an apple.
$final_string = str_replace('apple', '_apple_', $temp_string);
// $final_string is now: I like __apple_s_ very much. I want an _apple_.
This is not what I intend to do. I want the final string to be:
I like _apples_ very much. I want an _apple_.
This is what I tried to do:
$original_string = 'I like apples very much. I want an apple.';
$final_string = str_replace(['apples', 'apple'], ['_apples_', '_apple_'], $original_string);
echo $original_string;
// I like __apple_s_ very much. I want an _apple_.
Reversing the replacement order does not help either:
$original_string = 'I like apples very much. I want an apple.';
$original_string = str_replace(['apple', 'apples'], ['_apple_', '_apples_'], $original_string);
echo $original_string;
// I like _apple_s very much. I want an _apple_.
What should I do?
Thanks.
You can use preg_replace it use Regular Expression instead of string for the replacement
$original_string = 'I like apples very much. I want an apple.';
$final_string = preg_replace("/(apples?)/", "_$1_", $original_string);
echo $final_string;
Regex explanation : https://regex101.com/r/EzxqWR/2 and demo : https://3v4l.org/uTDIs
(1) (2)
vvvvvvvv vvvv
preg_replace("/(apples?)/", "_$1_", $original_string);
It will search string apple or apples
and will put the result to $1 and became _apple_ or _apples_
Hope the explanation is clear, and sorry for bad explanation

Reduce whole text to some words in PHP

I have a problem. I need a "text reducer".
What i mean: I wrote to text area any words, for example: John Doe is good boy; Then i press some button, and it will get something like:
John Doe
So, it will only output defined worlds, like John Doe, or milk or something like that
Thanks for your help
If you know a black list of words you want to strip out, you could use the array replace function: str_replace:
http://php.net/manual/en/function.str-replace.php
like this:
$blacklist = ['ugly', 'bad', 'censored'];
$yourString = str_replace($yourString, $blacklist, '');
This will remove every word in your blacklist, from your input string.
If you need a whitelist based filter, you could use split your string into an array of words, and then use the array_filter function:
http://php.net/manual/en/function.preg-split.php
http://php.net/manual/en/function.array-filter.php
using something similar to:
$whitelist = ['good', 'neat', 'stuff'];
$tokens = preg_split("/[\s,]+/", $yourString);
$filtered = array_filter($tokens, function ($item) {
return in_array($token, $whitelist);
});
$finalString = implode(' ', $filtered);
Yes you can write a function in this case it receives an array as parameter, but if is static, you could save it on the function.
Also, this could work using a regex with preg_match, but i'll leave that for you.
Currently ignores case thanks to `strtolower', if you don't want to ignore the case, remove this function calls.
function printWhiteListedText($arrWhitelist, $str){
$auxStr = "";
foreach($arrWhitelist as $word){
if(strpos(strtolower($str), strtolower($word)) > -1){
$auxStr .= $word . ' ';
}
}
return trim($auxStr);
}
echo printWhiteListedText(['Hello', 'world'], 'hello this world is great');

How to make str_ireplace same case

How to make str_ireplace same lowercase and uppercase.
example
$letters = array('jonny', 'gennie');
$fruit = array('ponny', 'petty');
$text = 'JONNY love Gennie';
$output = str_ireplace($letters, $fruit, $text);
echo $output;
so the actually output is :
ponny love petty
but i want like this
PONNY love Petty
how to do it? actually i just need it if first letter is uppercase or all letters are uppercase.
you're using explicit hard coded values in your example, so the easiest is to use str_replace instead of str_ireplace, and just do a pass for both lowercase and uppercase string replacements. You can simply build the uppercase and sentence case arrays off the lower case array, and then you don't even need to do any work:
$find_lc = array('moo', 'cow', 'something');
$find_uc = array_map('str_to_upper', $array);
$find_sc = array_map('ucfirst', $array);
$searches = array($find_lc, $find_uc, $find_sc);
$replace_lc = array(...);
$replace_uc = array(...);
$replace_sc = array(...);
$replacements = array($replace_lc, $replace_uc, $replace_sc);
$converted = $input;
for($i=0; $i<count($searches); $i++) {
$converted = str_replace($searches[$i], $replacements[$i], $converted);
}
And now it'll simply be correctly case-replaced. A little verbose perhaps, and you need hardcoded lists, but your question seemed pretty specific instead of asking about "any possible word" (in which case you'll need to use something like preg_replace_callback)

Is it possible to create a variable variable from a back reference in php?

Suppose I have this:
$t = "This %var% should be replaced";
$newText = preg_replace('/%(.+?)%/', "$1", $t);
What that does is replace the %var% for var, so the text becomes:
This var should be replaced.
But what I want to do is have a variable named $var, and then replace "%var%" with the value of $var.
We know that we can create variable variables like this:
$foo = "one";
$$foo = "two"
echo $one; //prints "two"
If you don't know about this, then you might not be able to answer my question. But you can read more about variable variables on http://www.php.net/manual/en/language.variables.variable.php
Well, that does not work in this case. If I do this:
$t = "This %var% should be replaced";
$newText = preg_replace('/%(.+?)%/', $"$1", $t);
I get an error.
I also tried like this:
$t = "This %var% should be replaced";
$newText = preg_replace('/%(.+?)%/', ${$1}, $t);
And I get another error.
The question is: how would I create a variable variable to replace %var% with the value of $var?
Some of you might ask why not just do this:
$t = "This %var% should be replaced";
$newText = preg_replace('/%(.+?)%/', $var, $t);
The reason is simple. The text I have is more complex than that. Lets make it more fun, shall we?
$text = "This %var% should be replaced, just like this %foo%;
$newText = preg_replace('/%(.+?)%/', "$1", $text);
As you can see, we need to replace %var% with the value of $var, and %foo% with the value of $foo.
I already solved the problem, but in a different way. But I am still wondering how it would be possible to solve it in this way, since the code is more readable. If it is not possible to solve it, then why?
Thanks for al your answers ans interest. Like I said I already solved the problem in a different way, and yes, I used preg_repace_callback. I am not looking for a solution to the problem, but for an explanation on why it is not possible to create a variable variable out of the backreference. I'm sorry if my question was confusing, or badly written and made you guys think I was still looking for a solution on how to achieve my goal.
If you wish to see how I solved it, you can go to my blog, I posted there yesterday about this: http://imbuzu.wordpress.com/2012/02/07/back-references-in-php-how-to-create-variable-variables-using-them/
Again. I am not looking for a way to do this, but rather for an explanation on why it is not possible to do it the way I initially intended. Why is it that you can't create a variable variable from the backreference?
To the Admins. This reply is a general reply to all the answers above. IF you are going to edit it and add it as a comment to any of them, please add it to all of them, or at least notify the users of this reply. Thanks.
What about an associative array?
$replacement = array('var' => 'value1',
'foo' => 'value2');
$text = "This %var% should be replaced, just like this %foo%";
$newText = preg_replace('/%(.+?)%/', $replacement[$1], $text);
You could use preg_replace_callback():
$var = '[replaced]';
function handler($found)
{
if ( isset($GLOBALS[$found[1]]) )
return $GLOBALS[$found[1]];
else
return $found[0];
}
$text = 'This %var% should be replaced and this %var2% will not be replaced!';
$newText = preg_replace_callback('/%(.+?)%/', 'handler', $text);
echo $newText;
This outputs the following:
This [replaced] should be replaced and this %var2% will not be replaced!
You must create a small parser with preg_X functions and an eval call. With these ingredients you can cook something like this:
<?php
$var = 'world';
$end = '.';
$t = "This %var% should be replaced%end%";
//We should escape " character
$t = str_replace('"','\"',$t);
$php = $t;
do
{
$orig_php = $php;
$php = preg_replace('/%([^%]+)%/','$\\1',$t);
} while($php!=$orig_php);
eval('$output="'.$php.'";');
echo($output);
?>
It's a tiny template engine

How to replace 2 strings (with eachother) simultaneously in PHP

What I'm trying to do is very simple, but I'm looking to do it most efficiently, preferably using php builtin fns.
$str = '1234';
echo replace_function(array('1','3'),array('3','1'),$str);
// output: 3214
str_replace,preg_replace would result in 1214, which means it goes through the arrays, replacing matched strings. I'm looking for a solution to simultaneously "switch" these two (or more) strings.
any ideas?
You need string translate:
http://php.net/manual/en/function.strtr.php
<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
// = hello all, I said hi
?>
<?php
$subject = '1234';
$result = preg_replace('/(1)(2)(3)(4)/si', '$3$2$1$4', $subject);
var_dump($result);
?>
You can change the pattern to something more generic, such as '/(\d)(\d)(\d)(\d)/'.

Categories