Reputation: 1093
I'm trying to work out how to find a match in a string.
I'm looking for a match on any of the following - = ? [] ~ # ! 0 - 9 A-Z a-z
and I need to know what its matched on .
Eg: matched on !
, or matched on =
and #
and ?
Normally I'd use this:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
However I'm not sure how to do that so it looks up the characters needed.
Also where I may have []
, It could be []
or [xxxx]
where xxxx could be any number of alpha numeric characters.
I need to match and any of the characters listed, return the characters so I know what was matched and if the [] contain any value return that as well.
Eg:
$a = 'DeviceLocation[West12]';
Would return: $match = '[]'; $match_val= 'West12';
$a = '#=Device';
Would return:$match = '#,=';
$a= '?[1234]=#Martin';
Would return: $match = '?, [], =, #'; $match_val= '1234';
Can any one advise how I can do this. Thanks
Upvotes: 1
Views: 1564
Reputation: 627488
Well, that requirements are a bit vague, but that is what I deduced:
1) if there is an alphanumeric string inside square brackets get it as a separate value
2) all other mentioned chars should be matched one by one and then implode
d.
You may use the following regex to get the values you need:
$re = '@\[([a-zA-Z0-9]+)\]|[][=?~#!]@';
Details:
\[
- a [
([a-zA-Z0-9]+)
- Group 1 value capturing 1 or more alphanumeric symbols\]
- a closing ]
|
- or[][=?~#!]
- a single char, one of the defined chars in the set.See the regex demo. The most important here is the code that gets the matches (feel free to adapt):
$re = '@\[([a-zA-Z0-9]+)\]|[][=?~#!]@';
$strs =array('DeviceLocation[West12]', '#=Device', '?[1234]=#Martin');
foreach ($strs as $str) {
preg_match_all($re, $str, $matches, PREG_SET_ORDER);
$results = array();
$match_val = "";
foreach ($matches as $m) {
if (!empty($m[1])) {
$match_val = trim($m[1], "[]");
array_push($results, "[]");
} else {
array_push($results, $m[0]);
}
}
echo "Value: " . $match_val . "\n";
echo "Symbols: " . implode(", ", $results);
echo "\n-----\n";
}
See the PHP demo
Output:
Value: West12
Symbols: []
-----
Value:
Symbols: #, =
-----
Value: 1234
Symbols: ?, [], =, #
-----
Upvotes: 1
Reputation: 1589
Try this
It will match the string in []
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
And this will match string after ?
and #=
preg_match_all("/^#=(\S+)|\?(.*)/", $text, $matches);
var_dump($matches);
Upvotes: 1
Reputation: 2442
You need regular expressions to check for any text inside another with different properties, here is a simple tutorial on that link.
Upvotes: 0