【发布时间】:2016-11-08 13:22:12
【问题描述】:
我有一个字符串:
"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"
找到第一个高度元素但我无法获取它之后的字符? 有任何想法吗? 提前致谢!
【问题讨论】: