php 在两个定界符之间爆炸并且定界符不丢失
php explode between two delimiter and delimiter not lost
如何分解定界符“[”之间的字符串,但我希望定界符不丢失
例如我有这样的字符串
$str = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]
我想要这样的结果
[0]=>
string(61) "i want to show you my youtube channel : [youtube id=12341234]"
[1]=>
string(68) "and my instagram account : [instagram id=myingaccount213]"
如果我使用 $tes = explode("]", $content);
,“]”会丢失
如果字符串只包含一个
$newStr = substr($str, strpos($str, '[') -1, strlen($str) - strpos($str, ']');
或
preg_match('/\[.+\]/', $str, $matches, PREG_OFFSET_CAPTURE);
除了拆分,您还可以通过匹配可选的水平空白字符来匹配您想要的部分,然后在组 1 中捕获尽可能少的字符,然后匹配 [...]
对于匹配项,使用 $matches[1]
获取第 1 组的值
\h*(.*?\[[^][]*])
示例代码
$s = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]";
preg_match_all("~\h*(.*?\[[^][]*])~", $s, $matches);
print_r($matches[1]);
输出
Array
(
[0] => i want to show you my youtube channel : [youtube id=12341234]
[1] => and my instagram account : [instagram id=myingaccount213]
)
另一种选择是使模式更适合 youtube 或 instagram:
\h*(.*?\[(?:youtube|instagram)\h+id=[^][\s]+])
请尝试:
$str = explode('|', str_replace('] ', ']|', $str));
如何分解定界符“[”之间的字符串,但我希望定界符不丢失 例如我有这样的字符串
$str = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]
我想要这样的结果
[0]=>
string(61) "i want to show you my youtube channel : [youtube id=12341234]"
[1]=>
string(68) "and my instagram account : [instagram id=myingaccount213]"
如果我使用 $tes = explode("]", $content);
,“]”会丢失
如果字符串只包含一个
$newStr = substr($str, strpos($str, '[') -1, strlen($str) - strpos($str, ']');
或
preg_match('/\[.+\]/', $str, $matches, PREG_OFFSET_CAPTURE);
除了拆分,您还可以通过匹配可选的水平空白字符来匹配您想要的部分,然后在组 1 中捕获尽可能少的字符,然后匹配 [...]
对于匹配项,使用 $matches[1]
\h*(.*?\[[^][]*])
示例代码
$s = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]";
preg_match_all("~\h*(.*?\[[^][]*])~", $s, $matches);
print_r($matches[1]);
输出
Array
(
[0] => i want to show you my youtube channel : [youtube id=12341234]
[1] => and my instagram account : [instagram id=myingaccount213]
)
另一种选择是使模式更适合 youtube 或 instagram:
\h*(.*?\[(?:youtube|instagram)\h+id=[^][\s]+])
请尝试:
$str = explode('|', str_replace('] ', ']|', $str));