'PHP Regex - get values between ^
Cannot figure this out.
I have string
^c1_e^,^d_e^,^c^
What would be the regex to get the values between^ and ^?
I tried
preg_match("/(?<=^).*?(?=^)/", $string, $match);
which doesn't work
Solution 1:[1]
An easier solution:
<?php
$string = '^c1_e^,^d_e^,^c^';
preg_match_all('/([^^,]+)/', $string, $matches);
$strings = $matches[1];
print_r($strings); //prints an array with the elements from $string
?>
Solution 2:[2]
You need to escape the carets. These by default mean 'beginning of line' in regex:
preg_match('/(?<=\^).*?(?=\^)/', $string, $match);
The above will get the , as well, but also only the first match. If you want to avoid the commas and get all the matches, you need to match the ^ and use a capture group:
preg_match_all('/\^([^^]+)\^/', $string, $match);
The array containing the parts in between the ^ will be in the array $match[1].
A non-regex solution (though a little less robust since it cannot work with a string in a format like ^abc,def^, ^abc^ where it should give out abc,def and abc) would be to split first, then remove the ^:
$theString = '^c1_e^,^d_e^,^c^';
$elements = explode(',', $theString);
for ($i = 0; $i < sizeof($elements); $i++) {
$elements[$i] = trim($elements[$i], "^");
}
print_r($elements);
Solution 3:[3]
You can also use this ~\^(.*?)\^~
<?php
$str="^c1_e^,^d_e^,^c^";
preg_match_all("~\^(.*?)\^~", $str,$match);
echo "<pre>";
print_r($match[1]);
OUTPUT :
Array
(
[0] => c1_e
[1] => d_e
[2] => c
)

Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Al.G. |
| Solution 2 | |
| Solution 3 | Shankar Narayana Damodaran |
