我想将变量值与文本文件行匹配,例如
$brands = 'Applica';
和文本文件内容如 -
'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'
由于文本文件中有四行。
并且每行的第一个字是与其等同品牌兼容的品牌。
与applica
类似,与Applica'和'布莱克和德克尔'和乔治福尔曼'
我希望将变量$brands
与单词applica
匹配,如果匹配则将其等于'Applica','Black and Decker','George Foreman'
的值等同于新变量。
请提供一些指导。
感谢。
更新 -
<?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";
}
?>
答案 0 :(得分:2)
这应该有效
$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);
如果品牌等于applica $ equalvalues,则等于:
array(3) {
[0]=>
string(7) "Applica"
[1]=>
string(16) "Black and Decker"
[2]=>
string(14) "George Foreman"
}
答案 1 :(得分:1)
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