简体   繁体   English

如何在php中使用preg_match匹配特殊字符?

[英]How to match special character using preg_match in php?

I have this 我有这个

$content1="W've have come across";
$content2="W've have come across all the oceans but still we don't find anything";

I have to strip out the content between "We've have come across" and "anything" 我必须删除“我们遇到过”和“任何事情”之间的内容

What kind of regex should I use when the content1,content2 can change but they may contain apostrophe's or special characters? 当content1,content2可以改变但是它们可能包含撇号或特殊字符时,我应该使用什么样的正则表达式?

How to use preg_match when you have special characters? 如果有特殊字符,如何使用preg_match?

preg_quote应该可以帮助你,但正如@Tomalak所说 - 为什么你不想使用str_replace或简单的东西(不是regexps)?

I use something like this: 我使用这样的东西:

function escape_regexp($regexp)
{
        $regex_chars = '^.[]$()|*+?{}' . "\\";
        $regexp = addcslashes($regexp, $regex_chars);

        return $regexp;
}

and then eg call: 然后打电话:

preg_replace('/something' . escape_regexp($var1) . 
    'something else/', '', $string)

I didn't use preg_quote() because I wanted function for general regexp escaping, not just for PHP, but also for mysql. 我没有使用preg_quote(),因为我想要通用regexp转义的函数,不仅适用于PHP,还适用于mysql。 I wanted a different character set. 我想要一个不同的角色集。 I didn't want charactes < and > to be escaped - I didn't find reason for escaping them. 我不希望字符<和>被转义 - 我没有找到逃脱它们的理由。

Without regexp, I'd use this : 没有正则表达式,我会用这个:

function weirdExtract($str, $start, $end){
    $posa = strripos($str, $start);
    $posb = strripos($str, $end);
    if($posa === false || $posb === false) return '';
    $startlen = strlen($start);
    return substr($str, $posa + $startlen, $posb - $startlen);
}

Used like this : http://codepad.viper-7.com/BJmEGG 像这样使用: http//codepad.viper-7.com/BJmEGG

strripos() can be changed with the appropriate function if case is important. 如果情况很重要,可以使用适当的函数更改strripos()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM