相关疑难解决方法(0)

正则表达式在第一场比赛时停止

我的正则表达式看起来像

<xxxx location="file path/level1/level2" xxxx some="xxx">
Run Code Online (Sandbox Code Playgroud)

我只对分配给位置的报价部分感兴趣.如果没有贪婪的开关,它不应该像下面那么容易吗?

/.*location="(.*)".*/
Run Code Online (Sandbox Code Playgroud)

似乎没有用.

regex

489
推荐指数
6
解决办法
54万
查看次数

用php preg_replace只替换字符串一次

我需要一个替换字符串一次功能,并相信preg_match可能是我最好的选择.

我正在使用它,但由于使用的动态性,有时这个函数表现得很奇怪:

function str_replace_once($remove , $replace , $string)
{
    $pos = strpos($string, $remove);
    if ($pos === false) 
    {
    // Nothing found
    return $string;
    }
    return substr_replace($string, $replace, $pos, strlen($remove));
} 
Run Code Online (Sandbox Code Playgroud)

现在我采用这种方法,但已经遇到下面列出的错误....我正在使用此函数解析所有类型的html字符串,因此很难给出导致错误的值.截至目前,我对以下80%的使用显示此错误.

function str_replace_once($remove , $replace , $string)
{
    $remove = str_replace('/','\/',$remove);
    $return = preg_replace("/$remove/", $replace, $string, 1);  
    return $return;
}  
Run Code Online (Sandbox Code Playgroud)

错误:

警告:preg_replace()[function.preg-replace]:编译失败:在偏移量0处不重复

有人可以改进解决方案吗?

php regex string

3
推荐指数
1
解决办法
3957
查看次数

标签 统计

regex ×2

php ×1

string ×1