我有一个字符串:
"This is the string. My height="200" and width="200".The second height="300" and width ="300""
如何扫描字符串并获取第一个高度元素并替换它?这意味着我只想抓住"height="200""
并替换它或完全删除它,但我如何扫描文件以查找第一次出现?同样对于我正在使用的实际字符串,我不知道高度设置为什么,所以我不能只搜索它。我想我需要找到"height="
并获取它后面的几个字符并更改它。我知道我可以使用以下方法进行搜索:
function str_replace_limit($search, $replace, $string, $limit = 1) {
$pos = strpos($string, $search);
if ($pos === false) {
return $string;
}
$searchLen = strlen($search);
for ($i = 0; $i < $limit; $i++) {
$string = substr_replace($string, $replace, $pos, $searchLen);
$pos = strpos($string, $search);
if ($pos === false) {
break;
}
}
return $string;
}
$search = 'height';
$replace = ' ';
$string = "This is the string. My height="200" and width="200".The second height="300" and width ="300"";
$limit = 1;
$replaced = str_replace_limit(($search), $replace, $string, $limit);
返回:
This is the string. My ="200" and width="200".The second height="300" and width ="300"
这找到了第一个高度元素,但我无法获得它后面的字符?有什么想法吗?提前感谢!
您可以使用preg_replace()
和一些正则表达式轻松做到这一点。使用preg_replace()
的"限制"选项(每个主题字符串中每个模式的最大可能替换数。默认值为 -1,表示无限制)可帮助您限制返回的匹配项数。将限制设置为 1 将返回第一个匹配项:
$subject = 'This is the string. My height="200" and width="200".The second height="300" and width ="300"';
$search = '/(height='")('d+)('")/';
$replace = 'height="450"';
$new = preg_replace($search, $replace, $subject, 1);
echo $new;
返回:
这是字符串。我的身高="450",宽度="200"。第二个高度="300",宽度="300"
正则表达式的解释:
第一捕获组
(height='")
--height=
字面上匹配字符height=
(区分大小写)——'"
字面意思是匹配字符"第二夺取组
('d+)
--'d+
匹配数字 [0-9]-- 量词:+
在一到无限次之间,次数为可能,根据需要回馈[贪婪]第3次捕获组
('")
--'"
与字面上的字符"
匹配
为了测试正则表达式,我使用了 regex101.com 来确保显示的正则表达式正常工作。给那些使用 regex101.com 的人的注意事项 - 始终应用 ''g 修饰符(用于全局匹配),因为 PHP 在使用正则表达式时几乎总是贪婪。
您正在搜索简单的文本,并且不会告诉您的函数应该搜索更多内容以及这个"更多"的外观。要实现这一点,您需要使用此处描述的preg_repalce
函数。你可以用这样的东西来重新包装你的函数
function str_replace_limit($search, $replace, $string, $limit = 1)
{
$pattern = '/' . $search . '="(.*?)"/';
return preg_replace($pattern, $replace, $string, $limit);
}
通过使用带有 limit
标志的函数preg_replace
可以轻松执行所需的替换(每个主题字符串中每种模式的最大可能替换。默认为 -1(无限制)。
$string = 'This is the string. My height="200" and width="200".The second height="300" and width ="300"';
$replaced = preg_replace("/ height=['"']'w+?['"']/", " ", $string, 1);
print_r($replaced);
// This is the string. My and width="200".The second height="300" and width ="300"