preg_match exact number
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开发者_如何学Go 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()
if( in_array(10, $ids) ) {
// do something
}
else {
// not found
}
In regex, if you want to find an exact match rather than just a substring match, you need to use start and end anchors. These are represented in regex by the ^
(start) and $
(end) characters.
So your regex to find "10" and not "110", etc, would be /^10$/
.
But if you're looking for a number, why not just use ==
or in_array()
?
PHP is quite capable of evaluating a numeric without having to parse it with regular expressions.
$regex = '/^10$/';
this will only match if the ^ is the beginning of the string, and the $ is the end of the string.
I'd use in_array()
as suggested by @Cfreak, but if you want to use regex to match an id of 10
you can do
preg_match('/[^\d]?10[^\d]?/', implode('|', $ids))
If you have array(1,10,1010,010)
, implode()
will change this to 1|10|1010|010
and the pattern will match against '10' not preceded or followed by any other digit (ie. another 0
or 1
as in 0101
)
精彩评论