Log in

View Full Version : Array within Regex value



bluewalrus
07-20-2010, 09:07 PM
Is there a way I can find a value in an array from a regular expression value?

I have an array of users and am trying to call the user in the array from the regular expression but am failing. I thought I'd asked this in the past but can't find it with the search.



$pattern = '/class="user">(\d+)<\/td>/';
$replace = "class=\"user\">$user[$1]</td>";
$user = preg_replace($pattern, $replace, $pending_tasks);

I think the $1 is being interrupted as a php variable which I don't want it to be.

james438
07-20-2010, 10:27 PM
I am pretty sure you need to escape your quotes in the pattern, but I have not tested it out.

Try reading up on preg_grep (http://us2.php.net/manual/en/function.preg-grep.php) for using regular esxpressions with arrays. I have not had the need to use this function either, but this should point you in the right direction.

djr33
07-20-2010, 11:17 PM
I would suggest looping through the array using foreach until you find that a key matches the regex. Maybe a little less efficient, but it shouldn't be too problematic and it's certainly easier to write. Unless, of course, there's something more complex to do that would make this not work.

bluewalrus
07-21-2010, 02:36 AM
Hmmm I got it to work using this but I think this isn't the most efficient way. Any suggestions? Thanks.



preg_match_all('/<td class="user">\d+<\/td>/', $pending_tasks, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
for($i = 0; $i < sizeof($val); ++$i) {
$user_key = preg_replace('/<td class="user">(\d+)<\/td>/', '$1', $val[$i]);
$pending_tasks = str_replace("<td class=\"user\">$user_key</td>", "<td class=\"user\">$user[$user_key]</td>", $pending_tasks);
}
}

djr33
07-21-2010, 04:38 AM
It is more code to write, but now that I think more about it, how is this really inefficient to any significant degree? Foreach runs, in general, very quickly, and the only slow part of that code is the regex which would be slow regardless of how you run it. Since you need to have that regex compared to the entire array, this format is basically the same amount of work required to do this using any method.
The only way it would be more efficient is if a default function were processed at a lower level, perhaps running faster. I don't know if this is the case with PHP, and in fact I don't think it is. I'm not sure though.