Should you initialize $matches before calling preg_match? - php

preg_match accepts a $matches argument as a reference. All the examples I've seen do not initialize it before it's passed as an argument. Like this:
preg_match($somePattern, $someSubject, $matches);
print_r($matches);
Isn't this error-prone? What if $matches already contains a value? I would think it should be initialized to an empty array before passing it in as an arg. Like this:
$matches = array();
preg_match($somePattern, $someSubject, $matches);
print_r($matches);
Am i just being paranoid?

There is no need to initialise $matches as it will be updated with the results. It is in effect a second return value from the function.

as Chris Lear said you don't need to initialize $matches. But if your pattern contains a capture group you want to use later, it is better to write:
$somePattern = '/123(456)/';
if (preg_match($somePattern, $someSubject, $matches)) {
print_r($matches[1]);
}
to avoid the error of undefined index in the result array. However, you can use isset($matches[1]) to check if the index exists.

Related

What am I doing wrong in this php regular expression?

I have a problem. I don't know what could be the cause. What I want to do is to know if an element of an array has a certain word, and I use this regular expression /.*example.*/, and this is the code:
$array = ['example1', '2example', 'no'];
$matches = [];
$var = "example";
foreach($array as $element)
{
preg_match("/.*$var.*/", $element, $matches);
}
But when I run the above code and see the value of $matches it is an empty array. What am I doing wrong?
That's because you are looping through your $array and probably print the result after the loop.
So $matches just includes the matching elements of the last item in your $array.
But because 'no' is the last element, and it doesn't fulfill the regex requirements, $matches is empty.
To have a better understanding of what is happening, try to use print_r($matches) within your loop, after you called preg_matches().
And after that, try to call it after your loop and see the difference.
You need two variables. One is the result of the current match, and another is a list of all the matches. After each call you can push the result of the current match to the list.
$array = ['example1', '2example', 'no'];
$matches = [];
$var = "example";
foreach($array as $element)
{
if (preg_match("/.*$var.*/", $element, $match)) {
$matches[] = $match[0];
}
}
print_r($matches);

How to save variable inside a database to use later

I don't know what to call this definition problem. I need to parse value from preg_match_all. before i get the value i want. I need to parse again the multidimensional array value return by preg_match_all.
The point is I need to reuse code with different value. The different only in variable $regex and $match[1][0]; In my database I have 2 columns. Regex value is pattern regex to match. The second column is $match[1][0] variable. What is call the definition?
I don't want to pass value variable $match[1][0]. but the $match[1][0]. and use it later with loop.
<?php
$temporary = "$match[1][0]";
preg_match_all($regex, $source, $match);
$match = $temporary;
echo $match;
You can try eval() function。It run a string with php code!
You can like this
$match = [
1 => [
[1]
]
];
$temporary = '$match[1][0]';
$match = eval('return $match[1][0];');
var_dump($match);

Filter array to keep values containing the search word using word boundaries

I know this type of question has been asked before and I also saw those working answers. However, it's not working when there are no space between the search string and the rest of the array value. Here is my code -
$example = array ( 'ext_03.jpg', 'int_01_headlight.jpg');
$searchword = 'int_';
$matches = array_filter($example, function($var) use ($searchword) {
return preg_match("/\b$searchword\b/i", $var);
});
echo array_values($matches)[0];`
The last value in the $example array doesn't have any space and this code doesn't work. However, if I put space after int_ it works. But I need it to work even if there are no spaces (should work when there is space too). How can I achieve that?
Here is the solution :
$example = array ( 'ext_03.jpg', 'int_01_headlight.jpg');
$searchword = 'int_';
$matches = array_filter($example, function($var) use ($searchword) { return
preg_match("/\b$searchword/i", $var); });
var_dump($matches);
Remove second \b : The \b in the pattern indicates a word boundary
Documentation : http://php.net/manual/en/function.preg-match.php
EDIT :
The better way is to use \A : Beginning of the string
$example = array ( 'ext_03.jpg', 'int_01_headlight.jpg', 'ext_ int_01_headlight.jpg');
$searchword = 'int_';
// Return 2 results (wrong way)
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword/i", $var); });
var_dump($matches);
// Return 1 result
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\A$searchword/i", $var); });
var_dump($matches);
When you wish to use a regular expression to filter an array, it is suboptimal to call preg_match() within array_filter().
The most appropriate call is preg_grep().
Try something like this:
$example = preg_grep('~\bint_~', $example);
You can extend the pattern with a character class after _ if your logic requires it.
But if you are only interested in the first match ([0]), then you might as well run a foreach() with preg_match() and a break.

PHP: Getting url variable with preg_match?

http://www.example.com?id=05
or
http://www.example.com?id=05&name=johnny
This is a string. And I want to get the value of $id from it.
What is the correct pattern for it?
You don't need regex (and you shouldn't be jumping straight to regex in the future unless you have a good reason).
Use parse_url() with PHP_URL_QUERY, which retrieves the querystring. Then pair this with parse_str().
$querystring = parse_url('http://www.mysite.com?id=05&name=johnny', PHP_URL_QUERY);
parse_str($querystring, $vars);
echo $var['id'];
#PhpMyCoder's solution is perfect. But if you absolutely need to use preg_match (though completely unnecessary in this case)
$subject = "http://www.mysite.com?id=05&name=johnny";
$pattern = '/id=[0-9A-Za-z]*/'; //$pattern = '/id=[0-9]*/'; if it is only numeric.
preg_match($pattern, $subject, $matches);
print_r($matches);

how to return matches value using preg_replace()

please how do that ?
<?php
$string = '<inc="file.php">';
return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#',include("$1"),$string);
?>
the output is return $1
i need to return include file.php
If you have PHP 5.3 or higher:
<?php
$string = '<inc="file.php">';
return preg_replace_callback('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#', function($matches) {
return include $matches[1];
}, $string);
?>
I think it should be
return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#','include("'.$1.'")',$string);
The second parameter should be a string.
I'm not exactly sure what you're trying to do, but try using preg_match over preg_replace.
It gathers the matches into an array if you use it like shown:
preg_match('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#', $string, $matches);
And then the matches are stored in the $matches array. You can then loop over them using foreach.

Categories