mor*_*t25 2 php regex preg-replace
尝试用PHP替换字符串($ content)中的height =""和width =""值,我试过preg替换无效,并建议我做错了什么?
示例内容如下:
$content = '<iframe width="560" height="315" src="http://www.youtube.com/embed/c0sL6_DNAy0" frameborder="0" allowfullscreen></iframe>';
Run Code Online (Sandbox Code Playgroud)
代码如下:
if($type === 'video'){
$s = $content;
preg_match_all('~(?|"([^"]+)"|(\S+))~', $s, $matches);
foreach($matches[1] as $match){
$newVal = $this->_parseIt($match);
preg_replace($match, $newVal, $s);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我只需要比赛并搜索我的身高和宽度
function _parseIt($match)
{
$height = "height";
$width = "width";
if(substr($match, 0, 5) === $height){
$pieces = explode("=", $match);
$pieces[1] = "\"175\"";
$new = implode("=", $pieces);
return $new;
}
if(substr($match, 0, 5) === $width){
$pieces = explode("=", $match);
$pieces[1] = "\"285\"";
$new = implode("=", $pieces);
return $new;
}
$new = $match;
return $new;
}
Run Code Online (Sandbox Code Playgroud)
可能有一个更短的方法来做到这一点,但是,我真的只是在6个月前选择了编程.
提前致谢!
你可以用preg_replace.它可以采用您想要匹配的正则表达式数组和替换数组.你想匹配width="\d+"和height="\d+".(如果你正在解析任意的html,你会想要扩展正则表达式以匹配可选的空格,单引号等)
$newWidth = 285;
$newHeight = 175;
$content = preg_replace(
array('/width="\d+"/i', '/height="\d+"/i'),
array(sprintf('width="%d"', $newWidth), sprintf('height="%d"', $newHeight)),
$content);
Run Code Online (Sandbox Code Playgroud)