Php 在字符串内搜索
每次更改此变量的值 我试图做的是从Php 在字符串内搜索,php,string,search,Php,String,Search,每次更改此变量的值 我试图做的是从[…]获取文本。因此,如果存在[(谷歌)],那么匹配项应该是(谷歌) 我正在寻找一个解决方案,它可以执行以下每个操作: 获取[…]的所有匹配项,写入$all 仅获取第一个匹配项,写入$first 仅获取最后一个匹配项,写入$last 从变量中删除[…]的所有匹配项(擦除) 只删除第一个匹配项 只删除最后一个匹配项 为此尝试了不同的正则表达式,如/[\(.*?\)]/,但结果并非预期的结果。这应该可以做到: $variable = 'of course it is
[…]
获取文本。因此,如果存在[(谷歌)]
,那么匹配项应该是(谷歌)
我正在寻找一个解决方案,它可以执行以下每个操作:
$all
$first
$last
/[\(.*?\)]/
,但结果并非预期的结果。这应该可以做到:
$variable = 'of course it is unnecessary [http://google.com],
but it is simple["very simple"], and this simple question clearly
needs a simple, understandable answer [(where is it?)] in plain English'
请注意,如果使用str_replace替换标记,则所有类似的标记都将被删除(如果存在),而不仅仅是第一个标记。应该有一种方法来删除所有、第一个或仅最后一个匹配项$first is[(它在哪里?)它应该是a(它在哪里?)(删除[and])@jcubic,有什么区别?括号是特殊的正则表达式字符,如果要匹配括号,必须将其转义。
$variable = 'of course it is unnecessary [http://google.com],
but it is simple["very simple"], and this simple question clearly
needs a simple, understandable answer [(where is it?)] in plain English';
preg_match_all("/(\[(.*?)\])/", $variable, $matches);
$first = reset($matches[2]);
$last = end($matches[2]);
$all = $matches[2];
# To remove all matches
foreach($matches[1] as $key => $value) {
$variable = str_replace($value, '', $variable);
}
# To remove first match
$variable = str_replace($first, '', $variable);
# To remove last match
$variable = str_replace($last, '', $variable);