好的,我找到了答案PHP - 将一串 HTML 属性拆分为索引数组
谢谢的
我想用%20
替换引号之间的每个空格字符
例:
<input type="text" title="this is a fish">
期望的结果:
<input type="text" title="this%20is%20a%20fish">
另一个例子
$_POST['foo'] = '<input type="text" title="this is a fish">';
$parsed = '<input type="text" title="this%20is%20a%20fish">';
正如所见,我只想替换 qoutes 中的空格,而不是任何其他空间。所以str_replace
在这里根本无济于事
最终结果是一个参数数组
这就是我所做的
<?php
$tag_parsed = trim($tag_parsed);
$tag_parsed = str_replace('"', '', $tag_parsed);
$tag_parsed = str_replace(' ', '&', $tag_parsed);
parse_str($tag_parsed, $tag_parsed);
但是当参数有空格时,它会中断。
更新
根据你最后的评论,你似乎需要这样的东西:
$str = '<input type="text" title="this is a fish">';
preg_match('/title="(.*)"/', $str, $title);
$parsed_title = str_replace(' ', '%20', $title[1]);
但似乎可以做一些事情来改进代码的其余部分。
您必须使用urlencode
或类似的功能:
$str = "Your spaced string";
$new = urlencode($str); //Your%20spaced%20string
或者,使用 preg_replace
:
$str = "Your spaced string";
$new = preg_replace("/'s+/", "%20", $str);
或者,没有正则表达式:
$new = str_replace(" ", "%20", $str);