Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.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_Regex_Html Parsing - Fatal编程技术网

php用正则表达式替换子字符串

php用正则表达式替换子字符串,php,regex,html-parsing,Php,Regex,Html Parsing,好吧,我知道有数万亿个类似的问题,但我发现要做到这一点真的很难。 我有一些这种格式的字符串: $x = '<iframe src="[File:19]"></iframe>'; $y = '<img src=[File:2212] />'; $z = '<source src="[File:42]" />'; 你能给我一些提示我怎么做吗 提前感谢。更改这两行 $rex = "/^.*(\[File:[0-9]{1,}\])/i" ; $file

好吧,我知道有数万亿个类似的问题,但我发现要做到这一点真的很难。 我有一些这种格式的字符串:

$x = '<iframe src="[File:19]"></iframe>';
$y = '<img src=[File:2212] />';
$z = '<source src="[File:42]" />';
你能给我一些提示我怎么做吗

提前感谢。

更改这两行

$rex = "/^.*(\[File:[0-9]{1,}\])/i" ;

$file = preg_replace ($rex, "http://lala.com/la.pdf", $file);
致:

这将把
[File…]
之前的内容捕获到组1中,然后在替换部分中,将该组(即
$1
)添加到替换字符串前面

它可以重写为:

$rex = "/\[File:\d+\]/i" ;

$file = preg_replace ($rex, "http://lala.com/la.pdf", $file);

这应该可以做到:

preg\u match('/\[文件:(\d+)\]/i',$str,$match)

$match[0]将包含整个字符串,$match[1]将仅包含数字。
在正则表达式匹配之后,可以使用
str_replace
从字符串中删除$match[0]

例如:

$x = '<iframe src="[File:19]"></iframe>';
preg_match('/\[File:(\d+)\]/i', $x, $match);
var_dump($match);
这应该起作用:

<?php
$formats[] = '<iframe src="[File:19]"></iframe>';
$formats[] = '<img src=[File:2212] />';
$formats[] = '<source src="[File:42]" />';


foreach( $formats as $format ) {

    $regex = '~\[File:(\d+)\]~';

    $replace = function( $matches ) {
        return 'http://lala.com/la.pdf?id=' . $matches[1];
    };

    var_dump( preg_replace_callback( $regex, $replace, $format ) );
}

您可以使用
preg\u match\u all
和删除
^.*
。。(应该有效)但实际上你应该使用它,因为它只是我,或者是
/^(.*)\[File
不仅是一个非常无用的部分,而且对性能非常有害?
/^.\[File/
归结为
/\[文件
,不是吗?如果你不在正则表达式中捕获它,你就不必替换它,对吗?@BerryLangerak:是的,你说得对,我只对OP的正则表达式进行了最小的更改。你不需要在parens中捕获整个表达式。默认情况下,整个匹配区域存储在$matches[0]中。
$x = '<iframe src="[File:19]"></iframe>';
preg_match('/\[File:(\d+)\]/i', $x, $match);
var_dump($match);
array(2) {
  [0]=>
  string(9) "[File:19]"
  [1]=>
  string(2) "19"
}
<?php
$formats[] = '<iframe src="[File:19]"></iframe>';
$formats[] = '<img src=[File:2212] />';
$formats[] = '<source src="[File:42]" />';


foreach( $formats as $format ) {

    $regex = '~\[File:(\d+)\]~';

    $replace = function( $matches ) {
        return 'http://lala.com/la.pdf?id=' . $matches[1];
    };

    var_dump( preg_replace_callback( $regex, $replace, $format ) );
}