Match variable value with text file row wise - php

I want to match variable value with text file rows, for example
$brands = 'Applica';
and text file content like -
'applica' = 'Applica','Black and Decker','George Foreman'
'black and decker' = 'Black and Decker','Applica'
'amana' = 'Amana','Whirlpool','Roper','Maytag','Kenmore','Kitchenaid','Jennair'
'bosch' = 'Bosch','Thermador'
As there are four rows in text file.
and first word of each row is brand which is compatible with their equal to brands.
like applica is compatible with 'Applica' and 'Black and Decker' and 'George Foreman'
I want to match variable $brands with word applica and if it matches then store their equal to value like 'Applica','Black and Decker','George Foreman' in new variable.
Please provide some guidance.
Thanks.
Update -
<?php
$brands = "brands.txt";
$contents = file_get_contents($brands);
$brandsfields = explode(',', $contents);
$csvbrand = 'applica';
foreach($brandsfields as $brand) {
$newname = substr($brand,1,-1);
echo $newname . "\t";
}
?>

This should work
$matches = explode("\n", "'applica' = 'Applica','Black and Decker','George Foreman'\n'black and decker' = 'Black and Decker','Applica'\n'amana' = 'Amana','Whirlpool','Roper','Maytag','Kenmore','Kitchenaid','Jennair'\n'bosch' = 'Bosch','Thermador'");
$brand = "applica";
$equalValues = [];
foreach ($matches as $key => $value) {
$keyMatch = str_replace("'", "", trim(explode('=', $value)[0]));
$valuesMatch = explode('=', $value)[1];
$escapedDelimiter = preg_quote("'", '/');
preg_match_all('/' . "'" . '(.*?)' . "'" . '/s', $valuesMatch, $matches);
if ($brand == $keyMatch) {
$equalValues = $matches[1];
}
}
var_dump($equalValues);
if brand is equal to applica $equalvalues shoud be equal to :
array(3) {
[0]=>
string(7) "Applica"
[1]=>
string(16) "Black and Decker"
[2]=>
string(14) "George Foreman"
}

preg_match_all("/'" . $csvbrand ."' = (.*)/", $contents, $output_array);
$names = explode(",", str_replace("'", "", $output_array[1][0]));
Var_dump($names); // results in ->
//Applica
//Black and Decker
//George Foreman

Related

How to replace a word (search_string) with the value of an array where the key is the search_string

I dont find the correct way to replace a word in a string where the word_to_be_replaced is a key and the word_to_replace_with is the corresponding value from a csv.
Example:
String: "The water is blue."
csv:
sky, ocean
colour, mood
water, painting
Expected outcome:
"The painting is blue."
I´m a beginner in php. I've asked a somewhat similar question - but I can´t make the answer I received work...
So far I´ve got:
$file = fopen("mods/test.csv","r");
while (($csv = fgetcsv($file)) !== false) {
$replace[$csv[0]] = $csv[1];
}
$blub = strtr($mpref, $replace);
What am I missing?
You should use str_replace. Check the Docs
You need to build 2 arrays, $search and $replace which will contain the values to be searched and replaced respectively.
$file = fopen("mods/test.csv","r");
$search = array();
$replace = array();
while (($csv = fgetcsv($file)) !== false) {
//$replace[$csv[0]] = $csv[1];
$search = $csv[0];
$replace = $csv[1];
}
$mpref = "The water is blue";
echo str_replace($search, $replace, $mpref);
//prints The painting is blue
Try this:
$file = fopen("mods/test.csv","r");
$search = array();
$replace = array();
while (($csv = fgetcsv($file)) !== false) {
$search = $csv[0];
$replace = $csv[1];
}
$mpref = "The water is blue";
echo str_replace($search, $replace, $mpref);
In above it will create an array of words to be replaced i.e. $search and array of world to be replaced with i.e. $replace. And str_replace consider arrays and replace a word in $search with the word in $replace having the same key index in both the arrays.
For more info check this str_replace()

How to separate mp3, mp4 file name from string using php?

Hi anyone can help I want separate mp3, mp4 from imploded data in PHP
my data string
$data = "song1.mp3, video1.mp4, song2.mp3"
i want to divide into two separate strings 1 string contains only mp4 with (,) separated and another with mp3
my data from database:
$data = "song1.mp3, video.mp4, song2.mp3";
$mp4 = video1.mp4,video2.mp4,..etc;
$mp3 = song1.mp3,song2.mp3,..etc;
thank you
Assuming your songs names are well formatted, meaning that they are named as title.suffix
<?php
$data = "song1.mp3, video.mp4, song2.mp3";
$mp3 = [];
$mp4 = [];
$song_names = explode(',', $data);
foreach ($song_names as $song_name) {
$song_name = trim($song_name);
$parts = explode('.', $song_name);
if (count($parts) == 2) {
$suffix = $parts[1];
if ($suffix == 'mp3') {
$mp3[] = $song_name;
} else if ($suffix == 'mp4') {
$mp4[] = $song_name;
}
}
}
//using implode so that we won't have an extra comma hanging in the end
$mp4 = implode(', ', $mp4);
$mp3 = implode(', ', $mp3);
?>
Use explode() to converting string to array by , delimiter. Then loop through array items and get extension of file name using substr() and check it.
$data = "song1.mp3, video1.mp4, song2.mp3";
$mp4 = $mp3 = "";
foreach (explode(",", $data) as $file){
$file = trim($file);
substr($file, -3) == "mp4" ? $mp4.=$file."," : $mp3.=$file.",";
}
$mp4 = substr($mp4, 0, -1);
$mp3 = substr($mp3, 0, -1);
Check result in demo
This sounds like a job for a preg_match_all() regex:
<?php
$string = 'song1.mp3, video.mp4, song2.mp3';
$regex = '#([^,\s]+\.mp3)#';
preg_match_all($regex, $string, $mp3s);
$regex = '#([^,\s]+\.mp4)#';
preg_match_all($regex, $string, $mp4s);
var_dump($mp3s[0]);
var_dump($mp4s[0]);
Which gives you:
array(2) { [0]=> string(9) "song1.mp3" [1]=> string(9) "song2.mp3" }
array(1) { [0]=> string(9) "video.mp4" }
Here's the code in action https://3v4l.org/2EmkR
Here's the docs for preg_match_all() http://php.net/manual/en/function.preg-match-all.php
Ok - a slightly different approach using pathinfo
$data = 'song1.mp3, video1.mp4, song2.mp3';
$mp3s = [];
$mp4s = [];
foreach (explode(', ', $data) as $file) {
$type = pathinfo($file)['extension'];
$type === 'mp3' ? $mp3s[] = $file : $mp4s[] = $file;
}
echo implode(', ', $mp4s) . PHP_EOL;
echo implode(', ', $mp3s) . PHP_EOL;
Could definitely use some validation and so forth but as an MVP it does the trick.

Reading information from CSS in PHP

I am creating a website where users shall be able to upload plugins with a file called 'info.css'. I want my PHP-file to be able to read out information from this file, for example the ID.
The 'info.css' file will contain something similar to:
/*
ID: test-preset;
Name: Test Preset;
*/
I want the ID and Name to get into separate strings, without the 'id:' or 'name:'.
Please write any solution you may will work. I have tried with following (but have gotten stuck on the way. Please note that the information in the 'info.css' file may appear in a different order, so for example it should work if the 'Name:' comes first.
$preset_inf = strtolower($preset_inf);
$preset_inf = explode('*/', $preset_inf);
$preset_inf = str_replace('/*', '', $preset_inf[0]);
$preset_inf = str_replace(' ', '', $preset_inf);
$preset_inf = explode(';', $preset_inf);
Regex?
$str = "/*
ID: test-preset;
Name: Test Preset;
*/";
preg_match_all("/(ID|Name):\s*(.*?)\;/s", $str, $m);
var_dump($m);
This will produce:
array(3) {
[0]=>
string(35) "ID: test-preset;
Name: Test Preset;"
[1]=>
string(11) "test-preset"
[2]=>
string(11) "Test Preset"
}
Matches anything between ID/Name and ;.
Edit noticed it could be the other way around too. Edited the code.
The output array will look slightly different but the part you want is in $m[2] array.
https://3v4l.org/iusmV
You can use regex to retrieve each variable, so:
preg_match( '/Name: (.*?);/', $css_file, $match );
$name = $match[1];
echo $name;
preg_match( '/ID: (.*?);/', $css_file, $match );
$id = $match[1];
echo $id;
Would return
Test Preset
test-preset
In case you need a more general solution, here is a regex that will parse a header with an arbitrary number of options along with their names:
$string = '/*
ID: test-preset;
Name: Test Preset;
*/';
$pattern = '/^(?!\/\*)([^:]+):([^:]+);$/mU';
preg_match_all($pattern, $string, $matches, PREG_SET_ORDER, 0);
$results = array();
foreach($matches as $match){
$results[$match[1]] = $match[2];
}
$results now contains an array with this structure:
[
"ID" => "test-preset",
"Name" => "Test Preset"
]
This has the benefit of being able to handle any number of "Header arguments".
Scalable solution.
$presetInfoItem = [];
$presetInfo = [];
$presetFile = "/*
ID: test-preset;
Name: Test Preset;
*/";
$fields = ['ID', 'Name'];
foreach ($fields as $field) {
$matchesCount = preg_match_all("#$field:(?'$field'[\w-\s]*);#", $presetFile, $presetInfoItem);
if ($matchesCount === 0 || $matchesCount === false) {
$presetInfo[$field] = "";
} else {
$presetInfo[$field] = trim($presetInfoItem[$field][0]);
}
}
var_export($presetInfo);
For your pleasure:
<?php
$css = '/*
ID: test-preset;
Name: Test Preset;
*/';
$css = str_replace("*/", "", $css);
$css = str_replace("/*", "", $css);
$css = str_replace(";", "", $css);
$css = trim($css);
$lines = explode("\n", str_replace("\r", '', $css));
if(!empty($lines)) {
foreach($lines as $i => $line) {
$vals = explode(":", $line);
$key = $vals[0];
$value = $vals[1];
echo '<div><b>'.$key.'</b>: '.$value.'</div>';
}
}
?>
Result is:
ID: test-preset
Name: Test Preset
Regex is not needed :)

How to Remove Hidden Characters in PHP

I have following piece of code, which reads text files from a director. I have used a list of stopwords and after removing stopwords from the files when the words of these files along with their positions then there come extra blank characters in place of where stopword exist in the document.
For example, a file which reads like,
Department of Computer Science // A document
after removing stop word 'of' from the document when I loop through the document then following output comes out:
Department(0) (1) Computer(2) Science(3) //output
But blank space should not be there.
Here is the code:
<?php
$directory = "archive/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$texts = preg_replace('/\s+/', ' ', $contents);
$texts = preg_replace('/[^A-Za-z0-9\-\n ]/', '', $texts);
$text = explode(" ", $texts);
$text = array_map('strtolower', $text);
$stopwords = array("a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "he", "in", "it","i","is", "its", "of", "on", "that", "the", "to","was", "were", "will", "with", "or", " ");
$text = (array_diff($text,$stopwords));
echo "<br><br>";
$total_count = count($text);
$b = -1;
foreach ($text as $a=>$v)
{
$b++;
echo $text[$b]. "(" .$b. ")" ." ";
}
}
}
closedir($dir);
?>
Genuinely not 100% sure about the final output of the string position, but assuming you are placing that there for reference only. This test code using regex with preg_replace seems to work well.
header('Content-Type: text/plain; charset=utf-8');
// Set test content array.
$contents_array = array();
$contents_array[] = "Department of Computer Science // A document";
$contents_array[] = "Department of Economics // A document";
// Set the stopwords.
$stopwords = array("a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "he", "in", "it","i","is", "its", "of", "on", "that", "the", "to","was", "were", "will", "with", "or");
// Set a regex based on the stopwords.
$regex = '/(' . implode('\b|', $stopwords) . '\b)/i';
foreach ($contents_array as $contents) {
// Remove the stopwords.
$contents = preg_replace($regex, '', $contents);
// Clear out the extra whitespace; anything 2 spaces or more in a row.
$contents = preg_replace('/\s{2,}/', ' ', $contents);
// Echo contents.
echo $contents . "\n";
}
The output is cleaned up & formatted like this:
Department Computer Science // document
Department Economics // document
So to integrate it into your code, you should do this. Note how I moved $stopwords & $regex outside of the while loop since it makes no sense to reset those values on each while loop iteration. Set it once outside of the loop & let the stuff in the loop just be focused on what you need there in the loop:
<?php
$directory = "archive/";
$dir = opendir($directory);
// Set the stopwords.
$stopwords = array("a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "he", "in", "it","i","is", "its", "of", "on", "that", "the", "to","was", "were", "will", "with", "or");
// Set a regex based on the stopwords.
$regex = '/(' . implode('\b|', $stopwords) . '\b)/i';
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
// Get the contents of the filename.
$contents = file_get_contents($filename);
// Remove the stopwords.
$contents = preg_replace($regex, '', $contents);
// Clear out the extra whitespace; anything 2 spaces or more in a row.
$contents = preg_replace('/\s{2,}/', ' ', $contents);
// Echo contents.
echo $contents;
}
}
closedir($dir);
?>
Just add \b after the pipe | operator as mentioned in the answer by Giacomo1968.
$regex = '/(' . implode('\b|\b', $stopwords) . '\b)/i';
It will work.

How to remove string with comma in a big string?

I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading
Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;
In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back
here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;
You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");

Categories