如何从字符串中提取带有分隔符的子字符串php
我想从具有分隔符的字符串中删除子字符串。如何从字符串中提取带有分隔符的子字符串php
例子:
$string = "Hi, I want to buy an [apple] and a [banana].";
如何获得“苹果”和“香蕉”出这个字符串,然后以数组?而字符串的其他部分“嗨,我想在另一个阵列中购买”和“和”。
我很抱歉如果这个问题已经得到解答。我搜索了这个网站,找不到任何能帮助我的东西。每种情况都有所不同。
preg_match_all('(?<=\[)([a-z])*(?=\])', $string, $matches);
应该做你想做的。 $matches
将是每个比赛的阵列。
你可以使用preg_split()
这样的:
<?php
$pattern = '/[\[\]]/'; // Split on either [ or ]
$string = "Hi, I want to buy an [apple] and a [banana].";
echo print_r(preg_split($pattern, $string), true);
,输出:
Array
(
[0] => Hi, I want to buy an
[1] => apple
[2] => and a
[3] => banana
[4] => .
)
可以剪裁的空白,如果你喜欢和/或忽略最终的句号。
谢谢戴夫!这看起来完全像我想要的。去尝试一下! –
@WandaEmbar认为你想要他们在一个数组中,然后在另一个数组中的“其他人”? – AbraCadaver
@WandaEmbar可能想回应问题的意见,要求澄清。 – AbraCadaver
我想你想的话作为数组中的值:使用preg_grep()
$words = explode(' ', $string);
$result = preg_grep('/\[[^\]]+\]/', $words);
$others = array_diff($words, $result);
- 创建一个空间
- 使用正则表达式使用
explode()
找到[somethings]
字的数组所有字的差异和[somethings]
使用array_diff()
,这将是字符串的“其他”部分
你是什么意思_和array_中字符串的其他部分?你希望单词是数组中的值吗? – AbraCadaver
对不起。没有看到问题。我想要另一个数组中的短语部分。所以“嗨,我想买一个”,“和一个”,“。” –
有质量答案的人将回顾你的问题历史,只是FYI – AbraCadaver