请帮我写正则表达式替换

时间:2012-09-14 09:11:56

标签: php regex

我还没有掌握正则表达式,所以非常感谢您对代码的帮助。

我需要替换以下所有行:

  1. 以括号或括号开头;
  2. ,可能包含常规数字最多3位数字或最多3个字母的组合;
  3. 可能会有一段时间;
  4. 其中的数字或数字可能在 标签内。
  5. 以下是需要替换的示例:

    (1)blahblah => %%(1)|blahblah
    (<i>iv</i>.) blahblah => %%(<i>iv</i>.)|blahblah
    [b] &nbsp;some stuff => %%[b]|&nbsp;some stuff
    

    因此正则表达式需要识别是否需要将其应用于特定字符串,如果是,则将%%放在行的开头,然后将这些内容放入括号中,然后放入管道。 (如果括号和文本的其余部分之间有空格,请删除空格),最后放置其余部分。

    所以,我们假设我有一个数组,我正在尝试运行该函数,该函数将处理字符串(如果它符合条件),或者保持不变。

    我只需要知道如何编写函数。

    由于

3 个答案:

答案 0 :(得分:3)

function my_replace ($str) {
    $expr = '~
        (
            # opening bracket or paren
            (?:\(|\[) 
                 # optional opening tag
                 (?:<([a-z])>)?
                 # either up to 3 digits or up to 3 alphas
                 (?:[a-z]{1,3}|[0-9]{1,3})
                 # optional closing tag
                 (?:</\2>)?
                 # optional dot
                 \.?
             # closing bracket or paren
             (?:\)|])
         )
         # optional whitespace
         \s*
         # grab the rest of the string
         (.+)
    ~ix';
    return preg_replace($expr, '%%$1|$3', $str);
}

See it working

答案 1 :(得分:2)

这是我的版本。

如果第一个正则表达式不匹配(如之前约定的那样),它将使用回退正则表达式。

<强> Demo

<强>代码:

<?php
function do_replace($string) {
    $regex = '/^(\((?:<([a-z])>)?(\d{0,3}|[a-z]{1,3})(?:<\/\2>)?(\.)?\)|\[(?:<([a-z])>)?(\d{0,3}|[a-z]{1,3})(?:<\/\2>)?(\.)?\])\s*(.*)/i';
    $result = preg_match($regex, $string);
    if($result) {
        return preg_replace($regex, '%%$1|$8', $string);
    } else {
        $regex = '/^(\d{0,3}|[a-z]{1,3})\.\s*(.+)$/i';
        $result = preg_match($regex, $string);
        if($result) {
            return preg_replace($regex, '%%$1.|$2', $string);
        } else {
            return $string;
        }
    }
}
$strings = array(
    '(1)blahblah',
    '(<i>iv</i>.) blahblah',
    '[b] &nbsp;some stuff',
    '25. blahblah',
    'A. some other stuff. one',
    'blah. some other stuff',
    'text (1) text',
    '2008. blah',
    '[123) <-- mismatch'
);
foreach($strings as $string) echo do_replace($string) . PHP_EOL;
?>

扩展了第一个正则表达式:

$regex = '
    /
        ^(
            \(
                (?:<([a-z])>)?
                (
                    \d{0,3}
                    |
                    [a-z]{1,3}
                )
                (?:<\/\2>)?
                (\.)?
            \)
            |
            \[
                (?:<([a-z])>)?
                (
                    \d{0,3}
                    |
                    [a-z]{1,3}
                )
                (?:<\/\2>)?
                (\.)?
            \]
        )
        \s*
        (.*)
    /ix';

答案 2 :(得分:-2)

function replaceString($string){
   return   preg_replace('/^\s*([\{,\[,\(]+?)/', "%%$1", $string);
}