preg_match('/^[ВBв][нnHN]\s*\[\s*[УуПпYy]\s*\]$/u', $str, $matches)
разбить на два массива в [matches] => Array
(
[0] => BH,
[1]=>[Y]
)
2 / 2
The preg_match pattern /^[ВBв][нnHN]\s*\[\s*[УуПпYy]\s*\]$/u is designed to match strings like "Вн [У]" or "BH[Y]" (with optional spaces around the square brackets) and capture the full match in $matches[0]. However, it does not create separate captures for "BH" and "[Y]" as shown in your desired output. To achieve the output [matches] => Array ( [0] => BH, [1] => [Y] ), you need to modify the pattern to include capture groups for the two parts explicitly.
Here’s how you can adjust the regular expression to split the match into two parts:
Modified Code
php
$str = "BH [Y]"; // Example input
preg_match('/^([ВBв][нnHN])\s*(\[\s*[УуПпYy]\s*\])$/u', $str, $matches);
print_r($matches);Explanation of the Pattern
- ^ - Start of the string.
- ([ВBв][нnHN]) - First capture group: Matches a single character from [ВBв] (В, B, or в) followed by a single character from [нnHN] (н, n, H, or N). This captures "BH", "Вн", etc.
- \s* - Matches zero or more whitespace characters (to allow optional spaces).
- (\[\s*[УуПпYy]\s*\]) - Second capture group: Matches a literal [ followed by optional whitespace, a single character from [УуПпYy] (У, у, П, п, Y, or y), optional whitespace, and a literal ]. This captures "[Y]", "[У]", etc.
- $ - End of the string.
- /u - Unicode modifier to handle Cyrillic characters correctly.
Example Output
For $str = "BH [Y]":
php
Array
(
[0] => BH [Y] // Full match
[1] => BH // First capture group
[2] => [Y] // Second capture group
)If you specifically want $matches[0] to be "BH" and $matches[1] to be "[Y]" (instead of $matches[1] and $matches[2]), you can reindex the array after preg_match:
Reindexing the Matches
php
$str = "BH [Y]";
preg_match('/^([ВBв][нnHN])\s*(\[\s*[УуПпYy]\s*\])$/u', $str, $matches);
$matches = array_slice($matches, 1); // Remove the full match, keep only capture groups
print_r($matches);Output
php
Array
(
[0] => BH
[1] => [Y]
)Notes
- The original pattern does not create separate capture groups for "BH" and "[Y]", so it only captures the full match in $matches[0].
- By adding parentheses () around the two parts of the pattern, you create two capture groups, which are stored in $matches[1] and $matches[2].
- If you need the exact indices [0] and [1] as shown in your example, use array_slice to reindex the matches array.
- The /u modifier ensures proper handling of Cyrillic characters like В, в, У, у, П, п.
- This solution assumes the input string follows the pattern (e.g., "BH [Y]", "Вн[У]", etc.). If the input can vary significantly, let me know, and I can adjust the pattern accordingly.
1s