Reputation: 81
I have a PHP script that loops through each row of a CSV file and organizes each line into an array:
$counter = 0;
$file = file($ReturnFile);
foreach($file as $k){
if(preg_match('/"/', $k)==1){
$csv[] = explode(',', $k);
$counter++;
}
}
...
while($x<$counter){
$line=$csv[$x];
This works; my question is about how to find a substring within each line. This:
foreach($line as $value){
if($value==$name_search){
// action
works if the value of $line
is exactly equal to the value of $name_search
($name_search
is a person's last name). However, this doesn't work if there is a space or additional characters in the value of $line
(for example: $line
equal to "Wilson (ID: 345)" or "Wilson " won't match a $name_search
value of "Wilson".
So far I've tried:
if(strpos($value, $res_name_search) !== false){
if(substr($value, 0, strrpos($value, ' '))==$res_name_search){
if(substr(strval($value), 0, strrpos(strval($value), ' '))==$res_name_search){
without success ... Do I have a syntax error and/or is there a better way to accomplish this?
Upvotes: 1
Views: 106
Reputation: 7805
I advice you to use fgetcsv function, this will return you an array of your columns for each iteration as follow :
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// ...
}
If in your CSV file, the column NAME is in position 2 for example and you want to know if token exist, just use
if (strpos('Wilson', $data[2] !== FALSE) {
// do your job
}
if you want to deal with case-insentivie, use stripos function
Upvotes: 0
Reputation: 2967
This is the sort of situations for which the built-in PHP function stristr
exists. This function is the case-insensitive equivalent of the strstr
function which, according to the docs:
Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.
Using this function, achieving such a task becomes as easy as:
foreach($line as $value){
if( stristr($value, $name_search) !== FALSE){
// substring was found in search string, perform your action
You can read more about it in the official documentation
I hope this helps.
Upvotes: 0
Reputation: 2359
You can also try this:
if (preg_match('/'.strtolower($res_name_search).'/', strtolower($value)))
Upvotes: 0
Reputation: 123
Try this:
$str = 'This is my test: wilson ';
$search = "wilson";
if(strpos(strtolower($str), strtolower($search)) !== false){
echo 'found it';
}
Upvotes: 0
Reputation: 2175
You can apply above mentioned points in your logic (Order of points may be different)
Upvotes: 0
Reputation: 67
Try to use strpos like this: if (strpos($res_name_search, $value))
Upvotes: 0
Reputation: 543
I think you have inverted the parameters. The following should work:
if (strpos($res_name_search, $value) !== false)
A minor note: use stripos
for case-insensitive search.
Upvotes: 1