How to get pattern matching in php array using RegEx - php

I have following set of an array
array('www.example.com/','www.example.com','www.demo.example.com/','www.example.com/blog','www.demo.com');
and I would like to get all element which matching following patterns,
$matchArray = array('*.example.com/*','www.demo.com');
Expected result as
array('www.example.com/','www.demo.example.com/','www.example.com/blog','www.demo.com');
Thanks :)

This works:
$valuesArray = array('www.example.com/','www.example.com','www.demo.example.com/','www.example.com/blog','www.demo.com');
$matchArray = array('*.example.com/*','www.demo.com');
$matchesArray = array();
foreach ($valuesArray as $value) {
foreach ($matchArray as $match) {
//These fix the pseudo regex match array values
$match = preg_quote($match);
$match = str_replace('\*', '.*', $match);
$match = str_replace('/', '\/', $match);
//Match and add to $matchesArray if not already found
if (preg_match('/'.$match.'/', $value)) {
if (!in_array($value, $matchesArray)) {
$matchesArray[] = $value;
}
}
}
}
print_r($matchesArray);
But I would reccomend changing the syntax of your matches array to be actual regex patterns so that the fix section of code is not required.

/\w+(\.demo)?\.example\.com\/\w*|www\.demo\.com/
regexr link

Related

manipulating array to use in different contex

I am using regex to match pattern. Then pushing matched result using pushToResultSet. In both way of doing, would $resultSet have similar array content? Similar means not
insense of value, but format. I want to use 2nd way in alternative to 1st code.
UPDATE: Example with sample input http://ideone.com/lIaP49
foreach ($words as $word){
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
$this->pushToResultSet($matches);
}
return $resultSet;
Now I am doing this in another way and pushing array in similar way. As $matches is array and here $b is also array, I guess both code are similar
$b = array();
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
foreach ($test as $value)
{
$value = strtolower($value);
// Capture also the numbers so we just concat later, no more string substitution.
$matches = preg_split('/(\d+)/', $value, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
if ($matches)
{
$newValue = array();
foreach ($matches as $word)
{
// Replace if a valid word number.
$newValue[] = (isset($arrwords[$word]) ? $arrwords[$word] : $word);
}
$newValue = implode($newValue);
if (preg_match($pattern, $newValue))
{
$b[] = $value;
$this->pushToResultSet($b);
}
}
}
//print_r($b);
return $resultSet;
UPDATE
ACtual code which I want to replace out with 2nd code in the question:
<?php
class Phone extends Filter{
function parse($text, $words)
{
$arrwords = array(0=>'zero',1=>'one',2=>'two',3=>'three',4=>'four',5=>'five',6=>'six',7=>'seven',8=>'eight',9=>'nine');
preg_match_all('/[A-za-z]+/', $text, $matches);
$arr=$matches[0];
foreach($arr as $v)
{
$v = strtolower($v);
if(in_array($v,$arrwords))
{
$text= str_replace($v,array_search($v,$arrwords),$text);
}
}
//$resultSet = array();
$l = strlen($text);
foreach ($words as $word){
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
//print_r($matches);
}
//print_r($matches);
$this->pushToResultSet($matches);
return $resultSet;
}
}
After running both codes, run PHP's var_dump function on the output variables.
If the printed output matches for your definition of similar array content, then your answer is yes. Otherwise, your answer is no.

Search for PHP array element containing string [duplicate]

This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
Closed 1 year ago.
$example = array('An example','Another example','Last example');
How can I do a loose search for the word "Last" in the above array?
echo array_search('Last example',$example);
The code above will only echo the value's key if the needle matches everything in the value exactly, which is what I don't want. I want something like this:
echo array_search('Last',$example);
And I want the value's key to echo if the value contains the word "Last".
To find values that match your search criteria, you can use array_filter function:
$example = array('An example','Another example','Last example');
$searchword = 'last';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
Now $matches array will contain only elements from your original array that contain word last (case-insensitive).
If you need to find keys of the values that match the criteria, then you need to loop over the array:
$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $v)) {
$matches[$k] = $v;
}
}
Now array $matches contains key-value pairs from the original array where values contain (case- insensitive) word last.
function customSearch($keyword, $arrayToSearch){
foreach($arrayToSearch as $key => $arrayItem){
if( stristr( $arrayItem, $keyword ) ){
return $key;
}
}
}
$input= array('An example','Another example','Last example');
$needle = 'Last';
$ret = array_keys(array_filter($input, function($var) use ($needle){
return strpos($var, $needle) !== false;
}));
This will give you all the keys whose value contain the needle.
It finds an element's key with first match:
echo key(preg_grep('/\b$searchword\b/i', $example));
And if you need all keys use foreach:
foreach (preg_grep('/\b$searchword\b/i', $example) as $key => $value) {
echo $key;
}
The answer that Aleks G has given is not accurate enough.
$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $v)) {
$matches[$k] = $v;
}
}
The line
if(preg_match("/\b$searchword\b/i", $v)) {
should be replaced by these ones
$match_result = preg_match("/\b$searchword\b/i", $v);
if( $match_result!== false && $match_result === 1 ) {
Or more simply
if( preg_match("/\b$searchword\b/i", $v) === 1 ) {
In agreement with http://php.net/manual/en/function.preg-match.php
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
I do not like regex because as far as I know, they are always slower than a normal string function. So my solution is:
function substr_in_array($needle, array $haystack)
{
foreach($haystack as $value)
{
if(strpos($value, $needle) !== FALSE) return TRUE;
}
return FALSE;
}
I was also looking for a solution to OP's problem and I stumbled upon this question via Google. However, none of these answers did it for me so I came up with something a little different that works well.
$arr = array("YD-100 BLACK", "YD-100 GREEN", "YD-100 RED", "YJ-100 BLACK");
//split model number from color
$model = explode(" ",$arr[0])
//find all values that match the model number
$match_values = array_filter($arr, function($val,$key) use (&$model) { return stristr($val, $model[0]);}, ARRAY_FILTER_USE_BOTH);
//returns
//[0] => YD-100 BLACK
//[1] => YD-100 GREEN
//[2] => YD-100 RED
This will only work with PHP 5.6.0 and above.

Using Regex to find if the string is inside the array and replace it + PHP

$restricted_images = array(
"http://api.tweetmeme.com/imagebutton.gif",
"http://stats.wordpress.com",
"http://entrepreneur.com.feedsportal.com/",
"http://feedads.g.doubleclick.net"
);
This are the list of images that I want to know if a certain string has that kind of string.
For example:
$string = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/".
Since "http://api.tweetmeme.com/imagebutton.gif" is in the $restricted_images array and it is also a string inside the variable $string, it will replace the $string variable into just a word "replace".
Do you have any idea how to do that one? I'm not a master of RegEx, so any help would be greatly appreciated and rewarded!
Thanks!
why regex?
$restricted_images = array(
"http://api.tweetmeme.com/imagebutton.gif",
"http://stats.wordpress.com",
"http://entrepreneur.com.feedsportal.com/",
"http://feedads.g.doubleclick.net"
);
$string = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/";
$restrict = false;
foreach($restricted_images as $restricted_image){
if(strpos($string,$restricted_image)>-1){
$restrict = true;
break;
}
}
if($restrict) $string = "replace";
maybe this can help
foreach ($restricted_images as $key => $value) {
if (strpos($string, $value) >= 0){
$string = 'replace';
}
}
You don't really need regex because you're looking for direct string matches.
You can try this:
foreach ($restricted_images as $url) // Iterate through each restricted URL.
{
if (strpos($string, $url) !== false) // See if the restricted URL substring exists in the string you're trying to check.
{
$string = 'replace'; // Reset the value of variable $string.
}
}
You don't have to use regex'es for this.
$test = "http://api.tweetmeme.com/imagebutton.gif/elson/test/1231adfa/";
foreach($restricted_images as $restricted) {
if (substr_count($test, $restricted)) {
$test = 'FORBIDDEN';
}
}
// Prepare the $restricted_images array for use by preg_replace()
$func = function($value)
{
return '/'.preg_quote($value).'/';
}
$restricted_images = array_map($func, $restricted_images);
$string = preg_replace($restricted_images, 'replace', $string);
Edit:
If you decide that you don't need to use regular expressions (which is not really needed with your example), here's a better example then all of those foreach() answers:
$string = str_replace($restricted_images, 'replace', $string);

Finding tags in query string with regular expression

I have to set some routing rules in my php application, and they should be in the form
/%var/something/else/%another_var
In other words i beed a regex that returns me every URI piece marked by the % character, String marked by % represent var names so they can be almost every string.
another example:
from /%lang/module/controller/action/%var_1
i want the regex to extract lang and var_1
i tried something like
/.*%(.*)[\/$]/
but it doesn't work.....
Seeing as it's routing rules, and you may need all the pieces at some point, you could also split the string the classical way:
$path_exploded = explode("/", $path);
foreach ($path_exploded as $fragment) if ($fragment[0] == "%")
echo "Found $fragment";
$str='/%var/something/else/%another_var';
$s = explode("/",$str);
$whatiwant = preg_grep("/^%/",$s);
print_r($whatiwant);
I don’t see the need to slow down your script with a regex … trim() and explode() do everything you need:
function extract_url_vars($url)
{
if ( FALSE === strpos($url, '%') )
{
return $url;
}
$found = array();
$parts = explode('/%', trim($url, '/') );
foreach ( $parts as $part )
{
$tmp = explode('/', $part);
$found[] = ltrim( array_shift($tmp), '%');
}
return $found;
}
// Test
print_r( extract_url_vars('/%lang/module/controller/action/%var_1') );
// Result:
Array
(
[0] => lang
[1] => var_1
)
You can use:
$str = '/%lang/module/controller/action/%var_1';
if(preg_match('#/%(.*?)/[^%]*%(.*?)$#',$str,$matches)) {
echo "$matches[1] $matches[2]\n"; // prints lang var_1
}

is there a native php function to see if one array of values is in another array?

Is there a better method than loop with strpos()?
Not i'm looking for partial matches and not an in_array() type method.
example needle and haystack and desired return:
$needles[0] = 'naan bread';
$needles[1] = 'cheesestrings';
$needles[2] = 'risotto';
$needles[3] = 'cake';
$haystack[0] = 'bread';
$haystack[1] = 'wine';
$haystack[2] = 'soup';
$haystack[3] = 'cheese';
//desired output - but what's the best method of getting this array?
$matches[0] = 'bread';
$matches[1] = 'cheese';
ie:
magic_function($haystack, %$needles%) !
foreach($haystack as $pattern) {
if (preg_grep('/'.$pattern.'/', $needles)) {
$matches[] = $pattern;
}
}
I think you are confusing $haystack and $needle in your question, because naan bread is not in haystack, nor is cheesestring. Your desired output suggests you are looking for cheese in cheesestring instead. For that, the following would work:
function in_array_multi($haystack, $needles)
{
$matches = array();
$haystack = implode('|', $haystack);
foreach($needles as $needle) {
if(strpos($haystack, $needle) !== FALSE) {
$matches[] = $needle;
}
}
return $matches;
}
For your given haystack and needles this performs twice as fast as a regex solution. Might change for different number of params though.
I think you'll have to roll your own. The User Contributed Comments to array_intersect() provide a number of alternative implementations (like this one). You would just have to replace the == matching against strstr().
$data[0] = 'naan bread';
$data[1] = 'cheesestrings';
$data[2] = 'risotto';
$data[3] = 'cake';
$search[0] = 'bread';
$search[1] = 'wine';
$search[2] = 'soup';
$search[3] = 'cheese';
preg_match_all(
'~' . implode('|', $search) . '~',
implode("\x00", $data),
$matches
);
print_r($matches[0]);
// [0] => bread
// [1] => cheese
You'll get better answers if you tell us more about the real problem.

Categories