Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/287.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在代码中查找数字,然后在第二次搜索时跳过第一个数字?_Php_String_Preg Match - Fatal编程技术网

PHP在代码中查找数字,然后在第二次搜索时跳过第一个数字?

PHP在代码中查找数字,然后在第二次搜索时跳过第一个数字?,php,string,preg-match,Php,String,Preg Match,我目前正在编写一个小代码,因为我的一所大学“销毁”了xml文档。我想在文档中找到所有y=“\d+”,并将数字增加+3。我的尝试是这样的: $path_to_file = 'testing.xml'; $file_contents = file_get_contents($path_to_file); if(preg_match('/y="\d+"/', $file_contents, $bef)){ $length = count($bef); for($i=0; $i<$

我目前正在编写一个小代码,因为我的一所大学“销毁”了xml文档。我想在文档中找到所有y=“\d+”,并将数字增加+3。我的尝试是这样的:

$path_to_file = 'testing.xml';
$file_contents = file_get_contents($path_to_file);
if(preg_match('/y="\d+"/', $file_contents, $bef)){
    $length = count($bef);
    for($i=0; $i<$length; $i++){
        if($bef[$i]!=0){
            $file_contents = str_replace($bef[$i], 'y="'. $bef[$i]+3 .'"', $file_contents);
        }
    }
    file_put_contents($path_to_file,$file_contents);
}
else{
    echo 'not found';   
}

希望它能帮助别人

你需要使用
preg\u match\u all
,因为
preg\u match
只返回
1
0
false

因此:

if (preg_match_all('/y="\d+"/', $file_contents, $matches)) {
    foreach ($matches as $match) {
        // $match will contain information about the current match
    }
}

这将调用
add_three
,以便在文档中进行匹配。

您可以使用。这应该使用适当的XML库(如SimpleXML)而不是正则表达式来完成。您可以发布需要处理的XML的一小部分吗?
preg\u match
允许您指定从搜索开始的位置开始的偏移量。但我认为使用
preg\u replace\u callback
会让这更容易…嘿,伙计们,找到了解决方案!preg_replace_回调工作正常!谢谢嘿,好的开始,但我认为这太复杂了,斯克拉加的解决方案很好:-)!完美的很好用。现在有一个问题。有一些y=“215.2”数字。我在哪里区分我的数字?我能用两种不同的图案吗?一个用于简单的215个数字,一个用于“215.2”个数字?我认为这是一个愚蠢的问题,因为它应该可以很好地工作:对代码进行了小修改:在add three函数中,您使用了“y=”+…,应该是“y=”。(3等)(代替+)@Fredrik好眼力。你能解释一下你打算如何区别对待浮点数吗?如果行为没有改变,这只是一个小的编辑,如果你正在做一些更困难的事情,我建议做两个函数和两个替换。是的,我想我需要两个替换。或者用php可以确定它是浮点数而不是整数,然后加上吗浮点数的+3?比如说如果它是“252.1”+3,那么总和就是“255.1”?
if (preg_match_all('/y="\d+"/', $file_contents, $matches)) {
    foreach ($matches as $match) {
        // $match will contain information about the current match
    }
}
$path_to_file = 'testing.xml';
$file_contents = file_get_contents($path_to_file);

$pattern = '/y="(\d+\.?\d*)"/'; // Optional dot follower by optional digits
$new_contents = preg_replace_callback($pattern, 'add_three', $file_contents);

file_put_contents($path_to_file,$new_contents);

function add_three($matches){
    return 'y="' . (3 + (float)$matches[1]) . '"'; // Cast to float not int, since we can do floats too
}