Replace array keys with values inside a string - php

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);
}

Related

How to transform preg_replace to wrap words from an array, instead just one word?

I have the following method, which checks for the word 'example' in a text, and if it finds is, it wraps a span around it:
function highlightWords($dreams) {
$wrap_before = '<span class="highlight_match">';
$wrap_after = '</span>';
$key_words = 'example';
$dreams = json_decode($dreams);
foreach ($dreams as &$value) {
$value->dream = preg_replace("/($key_words)/i",
"$wrap_before$1$wrap_after", $value->dream);
}
return $dreams;
}
I've tried to modify the $key_words variable to an array, so I could give multiple words as parameter, but it always gives back an error. Can I even do this with this approach?
Use implode() to convert your array of keywords into a string that you can use as your regex.
It appears that you want to do a whole word match on one of a number of keywords, so use the alternation operator (the | character) as a delimiter.
For example, given an array of:
$key_words = ['foo', 'bar', 'baz'];
$key_words = implode('|', $key_words);
Yields the following string:
foo|bar|baz
Which you can then use in place to create your regex of key words:
// /(foo|bar|baz)/i
preg_replace("/($key_words)/i",
"$wrap_before$1$wrap_after", $value->dream);
Hope this helps :)

PHP: Convert comma separated value pair string to Array

I have comma separated value pairs and I would like to convert it to associative array in php.
Example:
{
Age:30,
Weight:80,
Height:180
}
Converted to:
Echo $obj['Weight']; // 80
Does it make a difference that my values are not in inverted commas? I mean:
Weight:80
Vs
Weight:'80'
P.S. I've posted from a phone, so I don't have a lot of fancy markup available to make this question look more presentable.
http://php.net/manual/en/function.json-decode.php
It's an JSON object which you would like to convert to an array.
$string = '{ "Age":30, "Weight":80, "Height":180 }';
$array = json_decode($string, true);
echo $array['Age']; // returns 30
Provided that the given string is a valid JSON.
UPDATE
If that doesn't work because the string doesn't contain a valid JSON object (because I see the keys are missing double quotes), you could execute this regex function first:
$string = "{ Age:30, Weight:80, Height:180 }";
$json = preg_replace('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/u', '"$1"', $string); // fix missing quotes
$obj = json_decode($json, true);
echo $obj['Age']; // returns 30
When using the regex above, make sure the string doesn't contain any quotes at all. So make sure that not some keys have quotes and some not. If so, first get rid of all quotes before executing the regex:
str_replace('"', "", $string);
str_replace("'", "", $string);
You can get all values in an array by using this basic example:
// your string
$string = "{
Age:30,
Weight:80,
Height:180
}";
// preg_match inside the {}
preg_match('/\K[^{]*(?=})/', $string, $matches);
$matchedResult = $matches[0];
$exploded = explode(",",$matchedResult); // explode with ,
$yourData = array();
foreach ($exploded as $value) {
$result = explode(':',$value); // explode with :
$yourData[$result[0]] = $result[1];
}
echo "<pre>";
print_r($yourData);
Result:
Array
(
[Age] => 30
[Weight] => 80
[Height] => 180
)
Explanation:
(?<=}) look behind asserts.
K[^{] matches the opening braces and K tells what was matched.

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)

Delete a word from a string in mysql row

Am trying to delete a word from a string in my database
The string is $keywords = tech,sms,libya,tax
Suppose i want to remove libya from the string how do i go about this
I think for the clarity you might want to explode the string into an array, remove the unwanted element and then reconstruct the string. Like this:
$keywords = 'tech,sms,libya,tax'; // Set String
$keywords = explode(',', $keywords); // Explode into array
unset($keywords[ array_search('libya', $keywords) ]); // Unset the array element with value of 'libya'
$keywords = implode(',',$keywords); // Reconstruct string
Use MySQL's REPLACE function.

Replace names in text with links

I want to replace names in a text with a link to there profile.
$text = "text with names in it (John) and Jacob.";
$namesArray("John", "John Plummer", "Jacob", etc...);
$LinksArray("<a href='/john_plom'>%s</a>", "<a href='/john_plom'>%s</a>", "<a href='/jacob_d'>%s</a>", etc..);
//%s shout stay the the same as the input of the $text.
But if necessary a can change de array.
I now use 2 arrays in use str_replace. like this $text = str_replace($namesArray, $linksArray, $text);
but the replace shout work for name with a "dot" or ")" or any thing like that on the end or beginning. How can i get the replace to work on text like this.
The output shout be "text with names in it (<a.....>John</a>) and <a ....>Jacob</a>."
Here is an example for a single name, you would need to repeat this for every element in your array:
$name = "Jacob";
$url = "<a href='/jacob/'>$1</a>";
$text = preg_replace("/\b(".preg_quote($name, "/").")\b/", $url, $text);
Try something like
$name = 'John';
$new_string = preg_replace('/[^ \t]?'.$name.'[^ \t]/', $link, $old_string);
PHP's preg_replace accepts mixed pattern and subject, in other words, you can provide an array of patterns like this and an array of replacements.
Done, and no regex:
$text = "text with names in it (John) and Jacob.";
$name_link = array("John" => "<a href='/john_plom'>",
"Jacob" => "<a href='/jacob'>");
foreach ($name_link as $name => $link) {
$tmp = explode($name, $text);
if (count($tmp) > 1) {
$newtext = array($tmp[0], $link, $name, "</a>",$tmp[1]);
$text = implode($newtext);
}
}
echo $text;
The links will never change for each given input, so I'm not sure whether I understood your question. But I have tested this and it works for the given string. To extend it just add more entries to the $name_link array.
Look for regular expressions. Something like preg_replace().
preg_replace('/\((' . implode('|', $names) . ')\)/', 'link_to_$1', $text);
Note that this solution takes the array of names, not just one name.

Categories