preg_replace img 标签顺序 PHP
preg_replace img tag in sequence in PHP
我有一个内容,就像
Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test
我想把它改成
Test test test <id>1</id> test test <id>2</id> test test
我试过:
preg_match_all('/<img(.*?)alt=\"(.*?)\"(.*?)>/si', $content, $result, PREG_SET_ORDER);
foreach($result as $val) {
$content = preg_replace('/<img(.*?)alt=\"(.*?)\"(.*?)>/si', '<id>'.$val[2].'</id>', $content);
但它给了我:
Test test test <id>2</id> test test <id>2</id> test test
试试这个。
$data = `Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test`;
$replace = ["<img src='abc.png' alt='1'>","<img src='123.png' alt='2'>"];
$value = ["<id>1</id>","<id>2</id>"];
$dataNeeded = str_replace($replace, $value, $emailContent);
echo $dataNeeded;
您在 foreach 中的替换包含问题。这是固定版本。
<?php
$str = <<<term
Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test'
term;
preg_match_all('/<img.*?alt=[\'"](\d+)[\'"]>/', $str, $matches, PREG_SET_ORDER, 0);
foreach($matches as $val) {
$str = preg_replace('/<img.*?alt=[\'"](' . $val[1] . ')[\'"]>/', '<id>'.$val[1].'</id>', $str);
}
var_dump($str);
在这里查看:
http://sandbox.onlinephpfunctions.com/code/ad70f171ec5387451a29166865474de0f223f7c1
似乎 preg_match* 不是在这里使用的正确函数,需要循环就证明了这一点。只需 preg_replace():
即可完成
preg_replace("/<.*? alt=[\"']([0-9]+)[\"'] *>/", '<id></id>', $teststr);
这将独立地对每个匹配的表达式进行操作,并一次完成所有操作。如果您决定确实需要 src
值,则可以根据需要调整表达式。
我有一个内容,就像
Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test
我想把它改成
Test test test <id>1</id> test test <id>2</id> test test
我试过:
preg_match_all('/<img(.*?)alt=\"(.*?)\"(.*?)>/si', $content, $result, PREG_SET_ORDER);
foreach($result as $val) {
$content = preg_replace('/<img(.*?)alt=\"(.*?)\"(.*?)>/si', '<id>'.$val[2].'</id>', $content);
但它给了我:
Test test test <id>2</id> test test <id>2</id> test test
试试这个。
$data = `Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test`;
$replace = ["<img src='abc.png' alt='1'>","<img src='123.png' alt='2'>"];
$value = ["<id>1</id>","<id>2</id>"];
$dataNeeded = str_replace($replace, $value, $emailContent);
echo $dataNeeded;
您在 foreach 中的替换包含问题。这是固定版本。
<?php
$str = <<<term
Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test'
term;
preg_match_all('/<img.*?alt=[\'"](\d+)[\'"]>/', $str, $matches, PREG_SET_ORDER, 0);
foreach($matches as $val) {
$str = preg_replace('/<img.*?alt=[\'"](' . $val[1] . ')[\'"]>/', '<id>'.$val[1].'</id>', $str);
}
var_dump($str);
在这里查看: http://sandbox.onlinephpfunctions.com/code/ad70f171ec5387451a29166865474de0f223f7c1
似乎 preg_match* 不是在这里使用的正确函数,需要循环就证明了这一点。只需 preg_replace():
即可完成preg_replace("/<.*? alt=[\"']([0-9]+)[\"'] *>/", '<id></id>', $teststr);
这将独立地对每个匹配的表达式进行操作,并一次完成所有操作。如果您决定确实需要 src
值,则可以根据需要调整表达式。