正则表达式 - php - 获取空格不在前面,后面没有单词

时间:2013-01-03 12:01:06

标签: php regex

有这样的事情:

'This or is or some or information or stuff or attention here or testing' 

我想要捕获所有[空格],这些空格不在前面或后面跟着单词或。

我达到了这个目标,我想我已走上正轨。

/\s(?<!(\bor\b))\s(?!(\bor\b))/

或者

/(?=\s(?<!(\bor\b))(?=\s(?!(\bor\b))))/
但是,我没有得到所有的空间。这有什么问题? (第二个是尝试获得“和”去“)

3 个答案:

答案 0 :(得分:0)

试试这个:

<?php
    $str = 'This or is or some or information or stuff or attention is   not here or testing';
    $matches = null;
    preg_match_all('/(?<!\bor\b)[\s]+(?!\bor\b)/', $str, $matches);
    var_dump($matches);
?>

答案 1 :(得分:0)

(?<!or)\s(?!or)

怎么样?
$str='This or is or some or information or stuff or attention here or testing';
echo preg_replace('/(?<!or)\s(?!or)/','+',$str); 

>>> This or is or some or information or stuff or attention+here or testing

这使用了负面的lookbehind和lookahead,这将替换Tor operator中的空格,例如,如果你只想匹配or添加尾随和前面的空格:

$str='Tor operator';
echo preg_replace('/\s(?<!or)\s(?!or)\s/','+',$str); 

>>> Tor operator

答案 2 :(得分:0)

代码:(PHP Demo)(Pattern Demo

$string = "You may organize to find or seek a neighbor or a pastor in a harbor or orchard.";
echo preg_replace('~(?<!\bor) (?!or\b)~', '_', $string);

输出:

You_may_organize_to_find or seek_a_neighbor or a_pastor_in_a_harbor or orchard.

该模式有效地表明:

匹配每个空格 IF

  1. 该空格前面没有完整的单词“或”(以“或”结尾的单词不计算在内),并且
  2. 空格后没有完整的单词“或”(以“或”开头的单词不计算在内)
相关问题