0

I'm trying to figure out how I can compare values from an array against a particular string.

Basically my values look like chrisx001, chrisx002, chrisx003, chrisx004, bob001

I was looking at fnmatch() but I'm not sure this is the right choice, as what I want to do is keep chrisx--- but ignore bob--- so I need to wildcard the last bit, is there a means of doing this where I can be like

if($value == "chrisx%"){/*do something*/}

and if thats possible is it possible to double check the % value as int or similar in other cases?

chris
  • 36,115
  • 52
  • 143
  • 252
  • It's not clear where you want to do this comparison, but if you're after a quick way of getting an array of `chrisx`'s then you could also look at [`preg_grep()`](http://php.net/preg_grep). – salathe Jun 05 '12 at 17:59

2 Answers2

4

Regex can tell you if a string starts with chrisx:

if (preg_match('/^chrisx/', $subject)) {
  // Starts with chrisx
}

You can also capture the bit after chrisx:

preg_match('/^chrisx(.*)/', $subject, $matches);

echo $matches[1];
Mike B
  • 31,886
  • 13
  • 87
  • 111
  • ha, didn't even think about preg_match, guess sometimes the answers are inside the box, and not outside.. thanks – chris Jun 05 '12 at 17:50
  • @chris It's easy to get into the habit of trying to come up with the most clever, and sometimes obscure, way of accomplishing a goal. They're usually the most satisfying :) – Mike B Jun 05 '12 at 17:50
  • preg_match is the recommended regex system for PHP. The other one (ereg) is deprecated. http://stackoverflow.com/questions/1361591/php-ereg-vs-preg – starlocke Jun 05 '12 at 17:55
1

You could filter your array to return a second array of only those entries beginning whith 'chris' and then process that filtered array:

$testData = array ( 'chrisx001', 'chrisx002', 'chrisx003', 'chrisx004', 'bob001');
$testNeedle = 'chris';

$filtered = array_filter( $testData, 
                          function($arrayEntry) use ($testNeedle) { 
                              return (strpos($arrayEntry,$testNeedle) === 0); 
                          }
);

var_dump($filtered);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Mark Baker
  • 209,507
  • 32
  • 346
  • 385