str_replace alternative for PHP - php

In the str_replace manual for PHP it states the following:
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.
Is there an equivalent function that does not have this gotcha or how can I safely do this?

You're looking for strtr ( string $str , array $replace_pairs ).
If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.
Example from the manual:
<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
Will output:
hello all, I said hi
Which should be exactly what you need.

Use preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) im pretty sure you could make it replace all the values or one if thats what you're asking.
Or you could do it in pieces if theres an order to replace what you want
$value = preg_replace($pattern1, '..', $value);
$value = preg_replace($pattern2, '..', $value);
$value = preg_replace($pattern3, '..', $value);

Related

Echo words not found in string comparison

I have got a variable and an array (can be a variable as well) which need to be compared. I know how to compare two strings, but I don't know how to output the words which haven't been found. Also the words which haven't been found need to be in a variable so that I can use them later on.
$mystring = array('Net 40', 'Net 44', 'Priv 40');
$findme = 'Net 44';
if( strpos($mystring, $findme) !== false ) echo $findme." has been found in the string";
EDIT
I shall rephrase my question: How to compare two variables and output all words which haven't been found.
You could use array_diff to find the words that remain after you have successfully matched a word with one in a list:
$mystring = array('Net40', 'Net44', 'Priv40');
$findme = 'Net44';
echo "<br>list of words before: " . implode(",", $mystring);
$mystring = array_diff($mystring, array($findme));
echo "<br>list of words after: " . implode(",", $mystring);
Output:
list of words before: Net40,Net44,Priv40
list of words after: Net40,Priv40
strpos check that your second parameter is in the first parameter?
e.g.
strpos("This is", "is")
this checks that 'is' is in the string or not. If you want to check the result is in array or not please do as follows
if(in_array($findme,mystring)) echo $findme." has been found in the string";
First, you should not use strpos with an array and a string.
You could make something like this:
$mystring = array('Net 40', 'Net 44', 'Priv 40');
$findme = 'Net 44';
$size = count($mystring)
$notFound = array();
for($i = 0; $i < $size; $i++)
{
if($mystring[$i] === $findme)
{
echo $findme." has been found in the string (actually array)";
}
else
{
array_push($notFound, $mystring[$i]);
}
}
If mystring is actually supposed to be a string this code has to look a little bit different. I went with what you provided.
Solution with arrays. If your have strings, you can convert them to array with explode function.
<?php
$mystring = array('Net40', 'Net44', 'Priv40');
$findme = array('Net44');
$result=array_diff($mystring,$findme);
//$result is an array of elements that was in $mystring but not in $findme
print_r($result);
?>
Haven't been found is a little ambiguous, just be careful:
<?php
$haystack = array('Net40', 'Net44', 'Priv40');
$needles = array('Net44', 'NetBsd');
var_dump(array_diff($haystack, $needles));
var_dump(array_diff($needles, $haystack));
var_dump(array_intersect($haystack, $needles));
Output:
array (size=2)
0 => string 'Net40' (length=5)
2 => string 'Priv40' (length=6)
array (size=1)
1 => string 'NetBsd' (length=6)
array (size=1)
1 => string 'Net44' (length=5)

Something wrong with array

I'm using this code to get first number and replace it with 0-9, but I always get 0-0-9 result. Then I deleted in array 9 it started to work correct. why it works that way ?
$direction = strtoupper(substr($query_row["Band"],0,1));
$replace = [
'0' => '0-9','1' => '0-9','2' => '0-9','3' => '0-9','4' => '0-9',
'5' => '0-9','6' => '0-9','7' => '0-9','8' => '0-9', '9' => '0-9' ];
$dir= str_replace(array_keys($replace), $replace, $direction);
try this one
$search = array('0','1','2','3','4','5','6','7','8');
$replace = array('0-9','0-9','0-9','0-9','0-9','0-9','0-9','0-9','0-9');
$dir = str_replace($search, $replace, $direction);
and then work around for 9 which depends on your string
mine was 0123456789 so I tried
$dir = str_replace('99', '9,0-9', $dir);
its working on mine
It's explained in the documentation of str_replace():
Caution
Replacement order gotcha
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.
You pass arrays as first two arguments to str_replace(). This is the same as you would call str_replace() repeatedly for each element in the array.
If $direction is not '9' then it replaces it with '0-9'. Then, on the last cycle it replaces '9' from '0-9' with '0-9' (according to the values you passed it).
I would drop the code after the first line and read the first sentence again: "get first number and replace it with 0-9".
If your goal is to get the first character of $query_row["Band"] and replace it with 0-9 if it is a digit (and make it uppercase otherwise) I would write something more simple:
$direction = substr($query_row["Band"], 0, 1);
if (is_numeric($direction)) {
$dir = '0-9';
} else {
$dir = strtoupper($direction);
}

str_replace and arrays that are not in order

I'm stuck with this.
I've got a huge template that goes like this (simplified for this question):
$str = '[a] [b] [c]';
Then I have an array containing those above values:
$arr = array('[a]','[b]','[c]','[d]');
And finally, containing the values for replace comes an array that does not match the above one.
$rep = array("[d]" => "dVal","[a]" => "aVal","[b]" => "bVal", "[c]" => "cVal");
Can I some how, by some technique or any other php function match the $rep array to replace the key with the same name in $str. I current use str_replace.
sr_replace($arr,$rep,$str);//
The key names and names in $str are the same.
str_replace(array_keys($rep), array_values($rep), $str)

Replace array keys with values inside a string

I have a string of text:
$string = "This is a comment :) :D";
and an array of keys with values:
$smileys = Array(':)' => 'smile.gif', ':D' => 'happy.gif');
I want to replace any occurrences of array keys in the string with their related value so the output string would be:
$string = "This is a comment smile.gif happy.gif";
How can I do this? I've tried looping as below but no luck?
foreach($smileys as $smiley){
$string = preg_replace("~\b$smileys\b~", $smileys[$smiley], $string);
}
Edit
I also wish to add some html between the array and replace so:
:D
turns into
<img src="/happy.gif" />
but would the same html need to be in every array value if strtr were used?
try
$string= strtr($string,$smileys);
This will walk through $string and replace each occurence of each key in $smileys with the associated value.
Edit:
To include the <img> tags into the string you could post-process the whole string with a single
$string=preg_replace('/([\w]+\.gif)/i','<img src="$1">',$string);
This of course relies on the assumption that all your gif names do not contain any blanks and that there are no other words like image.gif in your string since they would be affected too ...
Try this:
foreach($smileys as $key => $value)
{
str_replace($key,$value,$string);
}
This should do
foreach($smileys as $key=>$value){
$string = str_replace($smiley[$key], $smiley[$value], $string);
}

How do I get the last part of a string in PHP

I have many strings that follow the same convention:
this.is.a.sample
this.is.another.sample.of.it
this.too
What i want to do is isolate the last part. So i want "sample", or "it", or "too".
What is the most efficient way for this to happen. Obviously there are many ways to do this, but which way is best that uses the least resources (CPU and RAM).
$string = "this.is.another.sample.of.it";
$contents = explode('.', $string);
echo end($contents); // displays 'it'
I realise this question is from 2012, but the answers here are all inefficient. There are string functions built into PHP to do this, rather than having to traverse the string and turn it into an array, and then pick the last index, which is a lot of work to do something quite simple.
The following code gets the last occurrence of a string within a string:
strrchr($string, '.'); // Last occurrence of '.' within a string
We can use this in conjunction with substr, which essentially chops a string up based on a position.
$string = 'this.is.a.sample';
$last_section = substr($string, (strrchr($string, '-') + 1));
echo $last_section; // 'sample'
Note the +1 on the strrchr result; this is because strrchr returns the index of the string within the string (starting at position 0), so the true 'position' is always 1 character on.
http://us3.php.net/strpos
$haystack = "this.is.another.sample.of.it";
$needle = "sample";
$string = substr( $haystack, strpos( $haystack, $needle ), strlen( $needle ) );
Just do:
$string = "this.is.another.sample.of.it";
$parts = explode('.', $string);
$last = array_pop(parts);
$new_string = explode(".", "this.is.sparta");
$last_part = $new_string[count($new_string)-1];
echo $last_part; // prints "sparta".
$string = "this.is.another.sample.of.it";
$result = explode('.', $string); // using explode function
print_r($result); // whole Array
Will give you
result[0]=>this;
result[1]=>is;
result[2]=>another;
result[3]=>sample;
result[4]=>of;
result[5]=>it;
Display any one you want (ex. echo result[5];)

Categories