highlight multiple word from file on php? - 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) );

Related

How to replace 'n\' from a string (not \n) in Php

I have a string which contains n\ by mistake (as imported from csv). So,I just want to replace n\ with \n.
Possible conditions : n\,\n\n, n\\n,n\n\
$string = "hello\n how n\n\ are you?\n\nis everything\nn\ok buddy, n\ where have you been. \n";
Try this. It will remove all the possible matches as per your question:-
$str = "main_string_goes_here";
$replace = "n\,\n\n,n\n\,\nn\,n\\n";
$arr = explode(",",$replace);
foreach($arr as $value)
{
str_replace($value,"\n",$str);
}
Happy Coding :-)
Use this:
str_replace("n\","\n",$string);
Here we search for the string, find the value "n\" and then replace the value with "\n". Update this example with your conditions.
Try like this
$string = 'hello\n how n\n\ are you?\n\nis everything\nn\ok buddy, n\ where have you been. \n';
$string = str_replace('n\\n\\','&new*',$string);
$string = str_replace('\\n\\n','&old*',$string);
$string = str_replace('n\\','\\n',$string);
$string = str_replace('&new*','\\n\\n',$string);
echo $string = str_replace('&old*','\\n\\n',$string);
Live demo : https://eval.in/904353
As other says to replace "n\" to "\n" will not work. You need to escape \ backslash also
Use this:
<?php
echo $string = 'hello\n how n\n\ are you?\n\nis everything\nn\ok buddy, n\ where have you been. \n';
$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);
echo $text = str_replace('n', '', $new_str);
?>
You can try this.
$string = 'hello\n how n\n\ are you?\n\nis everything\nn\ok buddy, n\ where have you been. \n';
echo str_replace('n\\', '\n',$string );

Replacing words from an array. 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).

Deleting spaces from a string

I have a form where people enter their multiple codes.
Now, I would like to delete the spaces between these codes.
However, my code doesnt seem to work. Any ideas?
$codes = $_GET['codes'];
$spaces = strpos($codes, " ");
for($spaces; $spaces=0; $spaces--){
str_replace(" ", "", $codes);
echo $codes;
}
EDIT: I just have tried something else but it still doesnt work at all. I mean the echo gives me the original string every single time.
$codes = $_GET['codes'];
$cleancodes = str_replace(" ", "", $codes);
$cleancodes = trim(preg_replace('/\s\s+/', ' ', $cleancodes));
echo "<br / >" . $cleancodes;
$string = str_replace(' ', '', $string);
$text=str_replace(" ","",$text);
But doing that for code? Bound to break (if you meant program code)!
Use str_replace():-
<?php
$_GET['codes'] = "abc def ghi jkl mno pqr stu vwx yz ";
$codes = $_GET['codes'];
$codes = str_replace(" ","",$codes);
echo $codes;
Output:-https://eval.in/395364

php remove the space in the beginning

I am having an array in PHP which contains some line breaks (\n) also as the array elements. I am writing these array elements into the CSV file using fwrite statement as below.
$newLine[] = $row[$i].",";
$newLine[] = "\n";
$csv2 [] = implode(" ", $newLine);
$file1 = fopen("/home/huadong/public_html/ramesh/output_updated.csv","w");
foreach ($csv2 as $line):
$line1 = ltrim($line);
fwrite($file1, $line1 . PHP_EOL);
endforeach;
fclose($file1);
ltrim is not working as it trims only leading white spaces. I have to replace the extra space in the beginning of the CSV file while it is getting written.
The CSV file is getting written as below.
Jack 1234
John 3456
Jason 3321
I am expecting to write into the CSV file as below.
Jack 1234
John 3456
Jason 3321
$newLine[] = $row[$i].",";
$newLine[] = "\n";
$csv2 [] = implode(" ", $newLine);
$file1 = fopen("/home/huadong/public_html/ramesh/output_updated.csv","w");
foreach ($csv2 as $line):
$line1 = ltrim($line," ");
fwrite($file1, $line1 . PHP_EOL);
endforeach;
fclose($file1);
You can use PHP's substr() function and a while loop, like this:
$name=" Jack 1234";
while(substr($name,0,1)==" ") $name=substr($name,1);
echo $name;//Jack 1234
Just change
$line1 = ltrim($line);
to this
$line1 = ltrim($line," ");

Remove special chars from URL

I have a product database and I am displaying trying to display them as clean URLs, below is example product names:
PAUL MITCHELL FOAMING POMADE (150ml)
American Crew Classic Gents Pomade 85g
Tigi Catwalk Texturizing Pomade 50ml
What I need to do is display like below in the URL structure:
www.example.com/products/paul-mitchell-foaming-gel(150ml)
The problem I have is I want to do the following:
1. Remove anything inside parentheses (and the parentheses)
2. Remove any numbers next to g or ml e.g. 400ml, 10g etc...
I have been banging my head trying different string replaces but cant get it right, I would really appreciate some help.
Cheers
function makeFriendly($string)
{
$string = strtolower(trim($string));
$string = str_replace("'", '', $string);
$string = preg_replace('#[^a-z\-]+#', '_', $string);
$string = preg_replace('#_{2,}#', '_', $string);
$string = preg_replace('#_-_#', '-', $string);
return preg_replace('#(^_+|_+$)#D', '', $string);
}
this function helps you for cleaning url. (also cleans numbers)
try this,
<?php
$url = 'http%3A%2F%2Fdemo.com';
$decodedurl= urldecode($url);
echo $decodedurl;
?
$from = array('/\(|\)/','/\d+ml|\d+g/','/\s+/');
$to = array('','','-');
$sample = 'PAUL MITCHELL FOAMING POMADE (150ml)';
$sample = strtolower(trim(preg_replace($from,$to,$sample),'-'));
echo $sample; // prints paul-mitchell-foaming-pomade
Try this:
trim(preg_replace('/\s\s+/', ' ', preg_replace("/(?:\(.*?\)|\d+\s*(?:g|ml))/", "", $input)));
// "abc (def) 50g 500 ml 3m(ghi)" --> "abc 3m"

Categories