I have the following code and I'm trying to achieve an effect like this
-Remove the "-" and number from the end of the string.
-Then check if the value is matching or not.
Here's my PHP code
$usernames= array("microsoft-2","google-1","google");
$value='google';
$input = preg_quote($value, '~');
$result = preg_grep('~' . $value . '~', $usernames);
echo '<pre>';
print_r($result);
//Array
(
[1] => google-1
[2] => google
)
The above results are fine but the problem is If I set value as "goog" it returns the same result while I'm expecting it to return an empty erray.
The usernames are coming from database and can be a large number.
In short it should return an remove the dash and number at the end and afterwards it should check if the values are same or not. If yes, then push in results otherwise not.
Any help would be appreciated ! Many Thanks
Add word break \b
$usernames= array("microsoft-2","google-1","google");
$value='goog';
$input = preg_quote($value, '~');
$result = preg_grep('~' . $value . '\b~', $usernames);
echo '<pre>';
print_r($result);
Output
array()
Sandbox
You can even add one to each side $result = preg_grep('~\b' . $value . '\b~', $usernames); in this case goog you only need the right one.
Related
I have an array
$array = ['download.png', 'download-1.png', 'download-2.png']
I want a regular expression that can match all three elements. So far I've tried and gotten something like
/('."$filename".')\-*[0-9]*$/
where $filename = 'download.png'
If it helps I am trying to use the regex in this
foreach($len as $value){
if(preg_match('/('."$filename".')\-*[0-9]*$/', $value->getValue()) ){
$array[] = $value->getValue();
var_dump( $array); echo '<br>';
}
}
help me anyone thanks in advance!
Try "/" . explode($filename, '.')[0] . "(?:-\d)?\.png/"
explode($filename, '.')[0] splits $filename into ['download', 'png'] and then gets the first element in that array, download.
(?:-\d)? is an optional (it's the ? that makes it optional) non-capturing group (that's the (?:) that matches a dash and then a number. This means that it's optional to match the -1.
From what I understand from your question, $value->getValue() is something like download-2.png. Your regex isn't matching the .png extension. I've added \.png to my regex for this.
An alternative solution without regex.
Explode on "-" if there is two items in the array it has "-" included in name.
$array = ['download.png', 'download-1.png', 'download-2.png'];
Foreach($array as $val){
$exp = explode("-", $val);
If(isset($exp[1])){
Echo "name is: " . $exp[0] . "-" . $exp[1] . "\n";
}Else{
Echo "name is: " . $exp[0] ."\n";
}
}
https://3v4l.org/5ElW3
I am trying to get the integer on the left and right for an input from the $str variable using REGEX. But I keep getting the commas back along with the integer. I only want integers not the commas. I have also tried replacing the wildcard . with \d but still no resolution.
$str = "1,2,3,4,5,6";
function pagination()
{
global $str;
// Using number 4 as an input from the string
preg_match('/(.{2})(4)(.{2})/', $str, $matches);
echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";
}
pagination();
How about using a CSV parser?
$str = "1,2,3,4,5,6";
$line = str_getcsv($str);
$target = 4;
foreach($line as $key => $value) {
if($value == $target) {
echo $line[($key-1)] . '<--low high-->' . $line[($key+1)];
}
}
Output:
3<--low high-->5
or a regex could be
$str = "1,2,3,4,5,6";
preg_match('/(\d+),4,(\d+)/', $str, $matches);
echo $matches[1]."<--low high->".$matches[2];
Output:
3<--low high->5
The only flaw with these approaches is if the number is the start or end of range. Would that ever be the case?
I believe you're looking for Regex Non Capture Group
Here's what I did:
$regStr = "1,2,3,4,5,6";
$regex = "/(\d)(?:,)(4)(?:,)(\d)/";
preg_match($regex, $regStr, $results);
print_r($results);
Gives me the results:
Array ( [0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5 )
Hope this helps!
Given your function name I am going to assume you need this for pagination.
The following solution might be easier:
$str = "1,2,3,4,5,6,7,8,9,10";
$str_parts = explode(',', $str);
// reset and end return the first and last element of an array respectively
$start = reset($str_parts);
$end = end($str_parts);
This prevents your regex from having to deal with your numbers getting into the double digits.
I want to get the words in a string where a specific character stands before, in this case, its the : character.
textexjkladjladf :theword texttextext :otherword :anotherword
From this snippet the expected output will be:
theword
otherword
anotherword
How do i do this with PHP?
You can use regular expression:
$string = "textexjkladjladf :theword texttextext :otherword :anotherword";
$matches = array();
preg_match_all('/(?<=:)\w+/', $string, $matches);
foreach ($matches[0] as $item) {
echo $item."<br />";
}
Output is:
theword
otherword
anotherword
The array what you want is the $matches[0]
Another way of getting those words without Regular Expression can be:
Use explode(' ',$str) to get all the words.
Then loop the words and check which one starts with ':'.
try
$str = 'textexjkladjladf :theword texttextext :otherword :anotherword';
$tab = exlode(':',$str);
print_r($tab);
//if echo entry 0 =>
echo $tab[0]; // => textexjkladjladf
I am using a explode and str_replace on the get parameter of the query string URL. My goal is to split the strings by certain characters to get to the value in the string that I want. I am having issues. It should work but doesn't.
Here are two samples of links with the query strings and delimiters I'm using to str_replace.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst
as you can see the URL above parameter is position and the value is data-analyst. The delimiter is the dash -.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst
and this URL above uses same parameter position and value is business+systems+analyst. The delimiter is the + sign.
The value I am trying to get from the query string is the word analyst. It is the last word after the delimiters.
Here is my code which should do the trick, but doesn't for some reason.
$last_wordPosition = str_replace(array('-', '+')," ", end(explode(" ",$position)));
It works if the delimiter is a + sign, but fails if the delimiter is a - sign.
Anyone know why?
You have things in the wrong order:
$last_wordPosition = end(explode(" ", str_replace(array('-', '+'), " ", $position)));
You probably want to split it up so as to not get the E_STRICT error when not passing an variable to end:
$words = explode(" ", str_replace(array('-', '+'), " ", $position));
echo end($words);
Or something like:
echo preg_replace('/[^+-]+(\+|-)/', '', $position);
As #MarkB suggested you should use parse_url and parse_str since it is more appropriate in your case.
From the documentation of parse_url:
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
From the documentation of parse_str:
Parses str as if it were the query string passed via a URL and sets variables in the current scope.
So here is what you want to do:
$url1 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst';
$url2 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst';
function mySplit($str)
{
if (preg_match('/\-/', $str))
$strSplited = split('-', $str);
else
$strSplited = split(' ', $str);
return $strSplited;
}
parse_str(parse_url($url1)['query'], $output);
print_r($values = mySplit($output['position']));
parse_str(parse_url($url2)['query'], $output);
print_r($values = mySplit($output['position']));
OUTPUT
Array
(
[0] => data
[1] => analyst
)
Array
(
[0] => business
[1] => systems
[2] => analyst
)
You said that you needed the last element of those values. Therefore you could find end and reset useful:
echo end($values);
reset($values);
Answering my own question to show how I ended up doing this. Seems like way more code than what the accepted answer is, but since I was suggested to use parse_url and parse_str but couldn't get it working right, I did it a different way.
function convertUrlQuery($query) {
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
$arrayQuery = convertUrlQuery($_SERVER['QUERY_STRING']); // Returns - Array ( [occupation] => designer [position] => webmaster+or+website-designer )
$array_valueOccupation = $arrayQuery['occupation']; // Value of occupation parameter
$array_valuePosition = $arrayQuery['position']; // Value of position parameter
$split_valuePosition = explode(" ", str_replace(array('-', '+', ' or '), " ", $array_valuePosition)); // Splits the value of the position parameter into separate words using delimeters (- + or)
then to access different parts of the array
print_r($arrayQuery); // prints the array
echo $array_valueOccupation; // echos the occupation parameters value
echo $array_valuePosition; // echos the position parameters value
print_r($split_valuePosition); // prints the array of the spitted position parameter
foreach ($split_valuePosition as $value) { // foreach outputs all the values in the split_valuePosition array
echo $value.' ';
}
end($split_valuePosition); // gets the last value in the split_valuePosition array
implode(' ',$split_valuePosition); // puts the split_valuePosition back into a string with only spaces between each word
which outputs the following
arrayQuery = Array
(
[occupation] => analyst
[position] => data-analyst
)
array_valueOccupation = analyst
array_valuePosition = data-analyst
split_valuePosition = Array
(
[0] => data
[1] => analyst
)
foreach split_valuePosition =
- data
- analyst
end split_valuePosition = analyst
implode split_valuePosition = data analyst
hi all i am trying to parse a big string and want to obtain only the value of id(id=dfsdfdsfdsfsaddfdfdfd) . My current code output extra data beyon the id value. could any one help me fix this problem.Thanks
preg_match_all("#live3.me.somesite.com([^<]+)\"#", $html, $foo);
print_r($foo[0]);
sample input string:
$html=".............."url":"rtmp:\/\/live3.me.somesite.com\/live\/?id=dfsdfdsfdsfsaddfdfdfd","name":"8.low.stream".........";
Is this an issue where you are set on using preg_match?
Or would something like 'parse_url' be acceptable?
http://php.net/manual/en/function.parse-url.php
Once parsed, getting specific query string parameters out should be easy
Just for the fun of answering an 8 month old question, here is my go at it :-)
We have got this to work with:
$html='".............."url":"rtmp:\/\/live3.me.somesite.com\/live\/?id=dfsdfdsfdsfsaddfdfdfd","name":"8.low.stream"........."';
That string sure looks a bit JSONish to me, so why not ...
// 1. Get rid of leading and trailing quotes and dots
$clean = trim($html, '"');
$clean = trim($clean, '.');
// 2. Add squiggly brackets to form a JSON string
$json = '{' . $clean . '}';
// 3. Decode the JSON into an array
$array = json_decode($json, true);
// 4. Parse URL value from the array and grab the query part
$query = parse_url($array['url'], PHP_URL_QUERY);
// 5. Get parameter values from the query
parse_str($query, $params);
// 6. Ta-da!
echo "Readable : ", $params['id'], PHP_EOL;
And of course ...
// The one-liner!
parse_str(parse_url(json_decode('{'.trim(trim($html,'"'),'.').'}', true)['url'], PHP_URL_QUERY), $params2);
echo "One-liner: ", $params2['id'], PHP_EOL;
Output:
Readable : dfsdfdsfdsfsaddfdfdfd
One-liner: dfsdfdsfdsfsaddfdfdfd