Replacing words from an array. PHP - php

I have file and I want to replace one word with another like in array. For example I have file.txt and array:
$arr = array(array("milk", "butter"), array("dog", "cat"))
So I want to replace all instances of "milk" with "butter" -- or all instances of "dogs" with "cats" in the text file.
How can I achieve this?

You can try like this;
<?php
// get file content
$text = file_get_contents("file.txt");
$arr = array(array("milk", "butter"), array("dog", "cat"));
foreach($arr as $val){
//replace text with your pattern
$text = str_replace($val[0],$val[1],$text);
}
echo $text;

This code replaces all occurrences of the first word of each inner array with the second word (the correspondent).
$txt = file_get_contents('file.txt'); //text example 'My dog loves milk. My cat loves butter.';
$words = array(array('milk', 'butter'), array('dog', 'cat'));
$result = $txt;
foreach($words as $word){
$result = str_replace($word[0], $word[1], $result);
}
echo 'Before: ' . $txt;
echo '<br>';
echo 'After: ' . $result;
file_put_contents('file2.txt', $result); // won't replace the file so you can see the difference.
Output:
Before: My dog loves milk. My cat loves butter.
After: My cat loves butter. My cat loves butter.
Notes:
This is one way: it doesn't change one by the other. It replaces the first with the second;
It's not checking for malformed;
It must be of same case (case sensitive).

Related

separate each words in php

I had an value in database like "demo text" . I want to display this content from the db in the view page as
Html code that i am using is like this <h2>Demo<span>Text</span></h2> , is there any solution for seperate each words and use one for h2 and other for span. I am using php codeigniter for the project , I don't know that whether the way i explained my problem is correct or not .
Yes you can so it with explode
if you have stored at least 2 words with space. try following
$demo ="demo text";
$arr = explode(" ",$demo);
$str = "<h2>".$arr[0]."<span>".$arr[1]."</span></h2>";
echo $str;
DEMO
EDIT
If you have more words and want to split first word only you can pass limit parameter in explode
$demo ="Pligrimage to Marian Shrines";
$arr = explode(" ",$demo,2);
$str = "<h2>".$arr[0]."<span>".$arr[1]."</span></h2>";
echo $str;
DEMO
I think you are looking for something like this!
$your_string = "Hello Houston! We have a problem!";
$my_array = explode(" ",trim($your_string));
$output = "<h2>";
foreach($my_array as $a_word){
if ($a_word === reset($my_array))
$output .= $a_word;
else
$output .= " <span>". $a_word . "</span>";
}
$output .= "</h2>";
print $output;

Filter a string for words that starts with a "?" and put them in a <span> - PHP

What I wanna do is filter a string like this one:
"?group This is a title"
And then output something like this:
<span class="group">group</span> This is a title
My question offcourse is: Is this possible with PHP? And how could I do something like this?
Try this
$text = preg_replace('/\?(\w+)/', '<span class="$1">$1</span>', $text);
This is what you need:
$string = "wordt bla shit happends and this wil be ?fat and ?this";
$array = array();
// Wanna search on other characters change the second ? and not the first. The first ? is part of the syntax.
preg_match_all('/(?<!\w)\?\w+/', $string, $array);
$result = $array[0];
foreach($result as $value){
$word = ltrim($value,'?');
// in your case change the html to whatever you want
$string = str_replace($value,"<b>$word</b>",$string);
}
echo $string;
result will be:
wordt bla shit happends and this wil be <b>fat</b> and <b>this</b>
$text = preg_replace('/\?(\w+)/', '<span class="$1">$1</span>', $text);

highlight multiple word from file on php?

I got a file filter.txt with words that I want to highlight on a string.
Filter.txt:
test1
test2
My solution doesen't work:
<?php
$file = file_get_contents('/home/user/filter.txt', true);
$keyword=$file;
$str="This is a test1 and test2 and test3";
$keyword = implode('|',explode(' ',preg_quote($keyword)));
$str = preg_replace("/($keyword)/i","<b>$0</b>",$str);
echo $str;
?>
Anyone?
took me like 15 mins but I eventually got it :)
<?php
$file = file_get_contents('/home/user/filter.txt', true);
$keywords = $file;
$str = "This is a test1 and test2 and test3";
$keywords = explode(" ", $keywords);
$str = preg_replace('/'.implode('|', $keywords).'/', '<b>$0</b>', $str);
echo $str;
?>
and this is expecting your filter.txt to be laid out like test1 test2 test3 etc. I'd suggest separating by new line or a pipe, |
try trimming the contents you might be getting a whitespace after the second keyword
$keyword=trim( file_get_contents("filter.txt",true) );

RegEx: How to extract a value/number from a pattern and replace it with something else?

For instance I have this piece of data:
array(
1 => 'Metallica',
2 => 'Megadeth',
3 => 'Anthrax',
4 => 'Slayer',
5 => 'Black Sabbath',
);
And I have this piece of text:
My first favorite band is: #band{2}, and after that it's: #band1. My
over-all first metal band was: #band{5}, and I sometimes enjoy
headbaning while listening to: #band3 or #band{4}.
So after the RegEx, it should look like this:
My first favorite band is: Megadeth, and after that it's: Metallica.
My over-all first metal band was: Black Sabbath, and I sometimes enjoy
headbaning while listening to: Anthrax or Slayer.
So, I need a pattern/example how can I extract numbers from these two patterns:
#band{NUMERIC-ID} or #bandNUMERIC-ID
No need for regular expressions, just use str_replace():
$map = array();
foreach ($bands as $k => $v){
$map["#band".$k] = $v;
$map["#band{".$k."}"] = $v;
}
$out = str_replace(array_keys($map), $map, $text);
A demo: http://codepad.org/uPqGXGg6
If you want to use regular expressions:
$out = preg_replace_callback('!\#band((\d+)|(\{(\d+)\}))?!', 'replace_band', $text);
function replace_band($m){
$band = $GLOBALS['bands'][$m[2].$m[4]];
return $band ? $band : 'UNKNOWN BAND';
}
A demo: http://codepad.org/2hNEqiCk
[edit] updated for multiple forms of the token to replace
try something like this
$txt = 'your text with bands';
foreach($arr as $key=>$val){
$txt = preg_replace('/#band'.$key.'([^0-9])/', $val.'$1', $txt);
$txt = preg_replace('/#band{'.$key.'}/', $val.'$1', $txt);
}
//detect the error
if(preg_match('/#band[^0-9]+/', $txt) || preg_match('/#band{[^0-9]+}/', $txt){
//error!!!
}
//replace the non found bands with a string
$txt = preg_replace('/#band[^0-9]+/', 'failsafe', $txt);
$txt = preg_replace('/#band{[^0-9]+}/', 'failsafe', $txt);

PHP: insert text up to delimiter

I have a bunch of chat logs that look like this:
name: some text
name2: more text
name: text
name3: text
I want to highlight the just the names. I wrote some code that should do it, however, I was wondering if there was a much cleaner way than this:
$line= "name: text";
$newtext = explode(":", $line,1);
$newertext = "<font color=red>".$newtext[0]."</font>:";
$complete = $newertext.$newtext[1];
echo $complete;
Looks fine, although you can save the temp variables:
$newtext = explode(":", $line,1);
echo "<font color=red>$newtext[0]</font>:$newtext[1]";
This might be faster or might not, you'd have to test:
echo '<font color=red>' . substr_replace($line, '</font>', strpos($line, ':') , 0);
The answer posted by gview is the simplest it gets, however and just as a reference you can use a regular expression to find the name tag, and replace it with the new html code using preg_replace() as follows:
// Regular expression pattern
$pattern = '/^[a-z0-9]+:?/';
// Array contaning the lines
$str = array('name: some text : Other text and stuff',
'name2: more text : : TEsting',
'name: text testing',
'name3: text Lorem ipsum');
// Looping through the array
foreach($str as $line)
{
// \\0 references the first pattern match which is "name:"
echo preg_replace($pattern, "<font color=red>\\0</font>:", $line);
}
also try the RegExp like this:
$line = "name: text";
$complete = preg_replace('/^(name.*?):/', "<font color=red>$1</font>:", $line);
echo $complete ;
EDIT
if their names aren't "name" or "name1", just delete the name in pattern, like this
$complete = preg_replace('/^(.*?):/', "<font color=red>$1</font>:", $line);

Categories