Regex Search Help - php

Given a string such as:
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
I want to find every integer within quotes and create an array of all integers found in the string.
End result should be an array like:
Array
(
[0] => 1
[1] => 2
)
I'm guessing you use preg_match() but I have no experience with regular expressions :(

How about this:
$str = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';
print_r(array_values(unserialize($str)));
Not a regex, same answer.
This works because the string you have is a serialized PHP array. Using a regex would be the wrong way to do this.

The regex (in a program) would look like this:
$str = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';
preg_match_all('/"(\d+)"/', $str, $matches);
print_r($matches[1]);

Related

Can't get regex to work. Empty returns

I've tried this regex on three different "regex generators" online. It works fine. But when I run it on my local machine I get empty arrays as response.
This is my code.
$string = "Testing \$test;";
preg_match_all("/(\$[A-Za-z]*)/", $string, $match);
print_r($match);
Response is:
Array
(
[0] => Array
(
[0] =>
)
[1] => Array
(
[0] =>
)
)
I've tried http://regexr.com/, https://regex101.com/#pcre, http://www.phpliveregex.com/
All work fine.
What is going on? Why is preg_match_all returning empty values on my machine? How can I debug this?
Thanks in advance
Because you used a double quoted string literal, you need to double backslashes:
preg_match_all("/(\\$[A-Za-z]*)/", $string, $match);
See the IDEONE demo
Otherwise, the $ with characters after it is parsed as a variable to expand.
That is why in most cases, a single quoted literal is preferred (demo) (as no variable expansion is expected inside it):
preg_match_all('/(\$[A-Za-z]*)/', $string, $match);

Pass a string into an array PHP

I have list of strings like this:
'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110
CL68035
release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'
It looks like elements of an array,
But when i use
<?php
$string = "'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'";
$arr = array($string);
print_r($arr);
?>
It doesnt work as I want:
Array ( [0] =>
'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110
CL68035
release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys')
Instead of:
Array ( [0] => PYRAMID, [1] => htc_europe, [2] => htc_pyramid,
...
I dont want to use explode() because my strings are already in array format and many strings have the ',' character.
Please help me, thanks.
Your string is not in an array format. From the way it looks and based on your comments, I would say that you have comma separated values, CSV. So the best way to parse that would be to use functions specifically made for that format like str_getcsv():
$str = "'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'";
// this will get you the result you are looking for
$arr = str_getcsv($str, ',', "'");
var_dump($arr);
The use of the second and third parameters ensures that it gets parsed correctly also when a string contains a comma.
$string is still a string, so you explode it if you want to make an array out of it.
If your problem is strings have the ',' character, use some other seperator, maybe |
$string = "'PYRAMID'|'htc_europe'|'htc_pyramid'|'pyramid'|'pyramid'|'HTC'|'1.11.401.110 CL68035 release-keys'|'htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'";
$arr = explode('|',$string);
print_r($arr);
<?php
$int = preg_match_all(
"/'(.+?)'/",
"'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'",
$matches);
print_r($matches[1]);
You can test it here http://micmap.org/php-by-example/en/function/preg_match_all
Due to the edits in the question, my answer is now out of date. I will leave it here because it contains a little explanation why in a particular case explode will be a valid solution.
as you can read in the manual online of php, there is a very precise syntax that can be used when creating an array, this is the reference:
http://php.net/manual/en/function.array.php
As you can see the correct way to use array() to create a new array is declaring each value separated by a comma or by declaring each pair index => value separated by a comma.
There is -no way- to pass a single string to that method (I see it something json like in javascript or java maybe, but this is Off Topic) simply because it won't parse it, the method will take the whole string as is and of course putting it into a single index (that in your case will be index zero).
I am telling you of course to use explode() or split() or to parse your string before, and what I told you before is the reason to my statement.
You probabily want to have each single model of phone in a string inside the array so you will have to remove the single quote first:
$stringReplaced = str_replace("'", "", $yourString);
And then you will have to split the string into an array using:
$array = explode(',',$yourString);
I hope you will take this in consideration
Of course as told by my collegue up there, you can treat this string as a comma separated value and use str_getcsv.
~Though you will need to remove the single quotes to have the pure string.~
(last statement is wrong because you can use the enclosure char param provided by str_getcsv)

preg_match bbcode

I currently have bbcode like this
[caption=Some text goes here]image.jpg[/caption]
I'd like to use php's preg_match so I can get the value of the image.jpg, regardless of what's next to 'caption='. Can someone help me out?
Raw regex:
]([^\]]+)[/caption]
preg_match("]([^\]]+)[/caption]", myString, $matches)
image.jpg would be in the first group. $matches[1]
(I'm not certain I escaped it correctly in php).
You can use this regex:
$str = '[caption=Some text goes here]image.jpg[/caption]';
if (preg_match('/^\[[^\]]+]([^[]+)/', $str, $arr))
echo "image: $arr[1]\n";
OUTPUT
image: image.jpg
If you want to match the complete bbcode tag, including the caption, use
preg_match("/\[caption=(.+)\](.+)\[\/caption\]/", $myString, $matches);
This will result in the following $matches array:
Array
(
[0] => [caption=Some text goes here]image.jpg[/caption]
[1] => Some text goes here
[2] => image.jpg
)
RegExp is not magic. PHP already has a pre-made extension library to handle BBCode.
Don't reinvent the wheel, and don't make it hard on yourself.

PHP preg_match part of url

I am trying to create a url router in PHP, that works like django's.
The problems is, I don't know php regular expressions very well.
I would like to be able to match urls like this:
/post/5/
/article/slug-goes-here/
I've got an array of regexes:
$urls = array(
"(^[/]$)" => "home.index",
"/post/(?P<post_id>\d+)/" => "home.post",
);
The first regex in the array works to match the home page at / but I can't get the second one to work.
Here's the code I am using to match them:
foreach($urls as $regex => $mapper) {
if (preg_match($regex, $uri, $matches)) {
...
}
}
I should also note that in the example above, I am trying to match the post_id in the url: /post/5/ so that I can pass the 5 along to my method.
You must delimit the regex. Delimiting allows you to provide 'options' (such as 'i' for case insensitive matching) as part of the pattern:
,/post/(?P<post_id>\d+)/,
here, I have delimited the regex with commas.
As you have posted it, your regex was being delimited with /, which means it was treating everything after the second / as 'options', and only trying to match the "post" part.
The example you are trying to match against looks like it isn't what you're actually after based on your current regex.
If you are after a regex which will match something like;
/post/P1234/
Then, the following:
preg_match(',/post/(P\d+)/,', '/post/P1234/', $matches);
print_r($matches);
will result in:
Array
(
[0] => /post/P1234/
[1] => P1234
)
Hopefully that clears it up for you :)
Edit
Based on the comment to your OP, you are only trying to match a number after the /post/ part of the URL, so this slightly simplified version:
preg_match(',/post/(\d+)/,', '/post/1234/', $matches);
print_r($matches);
will result in:
Array
(
[0] => /post/1234/
[1] => 1234
)
If your second RegExp is meant to match urls like /article/slug-goes-here/, then the correct regular expression is
#\/article\/[\w-]+\/#
That should do it! Im not pretty sure about having to escape the /, so you can try without escaping them. The tag Im guessing is extracted from a .NET example, because that framework uses such tags to name matching groups.
I hope I can be of help!
php 5.2.2: Named subpatterns now accept the syntax (?<name>) and
(?'name') as well as (?P<name>). Previous versions accepted only
(?P<name>).
http://php.net/manual/fr/function.preg-match.php

PHP Multiple digits regular expression

I need to extract the digits from the following string using regular expression:
pc 32444 xbox 43567
so my array will be
array ([0] => 32444 [1] => 43567)
Can someone help construct a preg_match for me?
Thanks!
Try this regular expression:
/\d+/
But you would need to use preg_match_all to get all matches:
preg_match_all('/\\d+/', $str, $matches)
$matches[0] will then contain the array you’re looking for.

Categories