Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP RegExp从撇号之间剥离字符串_Php_Regex - Fatal编程技术网

使用PHP RegExp从撇号之间剥离字符串

使用PHP RegExp从撇号之间剥离字符串,php,regex,Php,Regex,我在这里转圈转圈。我有这个字符串: document.write('£222,648.43'); 我想使用php/regexp以222648.43 这是迄今为止我得到的最接近的结果: preg_match('/\(\'(.*)\'\)/', $str, $matches); var_dump($matches); 这给了我: array (size=2) 0 => string '('£222,648.43')' (length=15) 1 => string '£222

我在这里转圈转圈。我有这个字符串:

document.write('£222,648.43');
我想使用php/regexp以
222648.43

这是迄今为止我得到的最接近的结果:

preg_match('/\(\'(.*)\'\)/', $str, $matches);
var_dump($matches);
这给了我:

array (size=2)
  0 => string '('£222,648.43')' (length=15)
  1 => string '£222,648.43' (length=11)
所以。。请问,如何去掉那个“£”字符

另外,作为帮助我进一步了解regexp的奖励,为什么会返回2个匹配项

谢谢

why are 2 matches returned?
因为一个来自捕获的组
()
,另一个用于与字符串匹配的整个模式

使用
preg\u replace

$content = preg_replace("/document\.write\('\D?([\d.,]+)'\);/", "$1", $content);
在这里,它将数字抓取到组
$1
,并用此捕获替换整个字符串

或者,您也可以使用此选项:

$content = preg_replace("/.*\('\D?([\d.,]+)'.*/", "$1", $content);

这里有一个相反的方法:

$string = "document.write('£222,648.43');";
$value = preg_replace("/[.,]*[^\d,.]+[.,]*/", "", $string);
您可以使用:

$str = "document.write('£222,648.43');";
echo preg_replace_callback("~^.*?\( *'([^']+)' *\).*?$~", function($m) {
       return preg_replace('~[^\d,.]+~', '', $m[1]);
    }, $str); 
//=> 222,648.43

返回的第一个匹配将是整个正则表达式上的匹配。第二个将是第一个捕获组(括号中)

如果要删除开头引号后的第一个字符,可以使用括号中捕获部分之前的
,匹配任何字符:

'/\(\'.(.*)\'\)/'
如果您只需要在字符为“£”时将其删除,则可以在进入捕获组之前添加
£
,以可选地匹配符号:

'/\(\'£?(.*)\'\)/'
如果需要删除其他可能的货币符号,可以将它们包含在字符类中,如
[£$€¨8362; 8361;₤﷼],例如:

'/\(\'[£$€¥₪₩₤﷼]?(.*)\'\)/'

你忘了“文件”和“写”之间的点.嗨,谢谢,我使用了另一种解决方案,但很高兴看到它也可以像那样向后处理。非常感谢,我使用了最后一种解决方案,因为这将涵盖多个基础和多个货币。感谢对双匹配的解释。谢谢,我使用了一种更简单的解决方案,但非常感谢您的时间。