Reputation: 17352
I want to check if a string has the character "|" (only one time and not at the beginning or end of the string). If this is the case the string should be splitted. The second check is if the first part is "X" or not.
Example:
$string = "This|is an example"; // Output: $var1 = "This"; $var2 = "is an example";
RegEx is really difficult for me. This is my poor attempt:
if (preg_match('/(.*?)\|(.*?)/', $string, $m)) {
$var1 = $m[1];
$var2 = $m[2];
if ($var1 == "X") // do anything
else // Do something else
Upvotes: 0
Views: 77
Reputation: 10033
If you don't know regex you might want a solution which doesn't use regex.
$test = ["|sdf", "asd|asad", "asd|", "asdf", "sd|sdf|sd"];
foreach ($test as $string) {
$res = explode("|", $string);
if (2 === count($res) && strlen($res[0]) && strlen($res[1])) {
var_dump($res);
}
}
Result:
array(2) {
[0]=>
string(3) "asd"
[1]=>
string(4) "asad"
}
Upvotes: 1
Reputation: 215009
A pure regex solution would be:
^ -- start of input
[^|]+ -- some non-pipes
\| -- a pipe
[^|]+ -- some non-pipes
$ -- finita la comedia
However, string functions might work better in this case, since you're going to split it anyways:
$x = explode('|', $input);
if(count($x) == 2 && strlen($x[0]) && strlen($x[1]))
// all right
Upvotes: 3