I’m using
$regex = '/'.implode('|', 10).'/i';
preg_match($regex, $ids)
to find the number 10 in a list of IDs ($ids). However, if the list of IDs looks like this:
$ids = array(10, 110, 1010);
Would it bring back all of them? How can I make it find the exact number I am after, and not just find a number that contains the number I’m after?
Thanks.
Edit:
I made a mistake above. The list of IDs is actually a string of comma separated values. For example:
$ids = "10,1010,101";
It’s hard to explain the whole idea process behind this, but this is my full code:
<?php
$file = fopen('allprods.csv', 'r');
$id = array($_GET['id']);
$id = array_map('preg_quote', $id);
$regex = '/'.implode('|', $id).'/i';
$skus = array();
while (($line = fgetcsv($file)) !== FALSE) {
list($ids, $sku) = $line;
if(preg_match($regex, $ids)) {
$skus[] = $sku;
}
}
$count = count($skus);
$i = 1;
echo $category_id;
foreach ($skus as $sku){
echo $sku;
if($i != $count) { echo "`"; }
$i++;
}
I’m essentially rooting through a csv that has an ID column (some rows have multiple ids in that column, spearated by commas), and an sku column. More info here
So I need the code to check the string of ids for a certain ID, for example 10, and then add the appropriate SKU to an sku array.
I’m sure this code is a mess, so bear with me while I hack PHP to bits!
Edit: This is now solved! I used in_array instead, as mentioned in the answers. First of all I exploded the comma separate string. Code can be seen below:
$skus = array();
while (($line = fgetcsv($file)) !== FALSE) {
list($ids, $sku) = $line;
$cats = explode(',',$ids);
if (in_array($_GET['id'], $cats)) {
$skus[] = $sku;
}
}
Thanks for the help all.
Don’t use a regex for this. Use
in_array()