【问题标题】:Replace every white space character between quotes [duplicate]替换引号之间的每个空格字符[重复]
【发布时间】:2023-03-07 03:18:02
【问题描述】:

好的,我找到了答案 PHP - split a string of HTML attributes into an indexed array

谢谢

我想用%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);

但是当参数有空格时,它会中断。

【问题讨论】:

  • 输出->foo o
  • @DenisAlexandrov 这不是我要问的,我有一个示例中的字符串,我不想替换每个空格,只是替换 qoutes 中的那些
  • @MordiSacks,但是,功能是相同的。你只需要正确使用它们。示例:&lt;input type="text" title="&lt;?= str_replace(' ', '%20', 'this is a fish') ?&gt;"&gt;
  • 再一次,我不创建字符串,我接收它,所以我不能在其中调用函数
  • 您能否通过此流程更新您的问题,以便我们了解发生了什么?

标签: php regex


【解决方案1】:

更新

根据您上次的 cmets,您似乎需要这样的东西:

$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);

【讨论】:

  • 这对我没有帮助,因为当我有字符串时,它就像示例中一样,而不仅仅是文本
  • 好的,我已经更新了我的答案。试试preg_replacestr_replace。并且,检查 dup 链接
猜你喜欢
  • 2014-12-11
  • 1970-01-01
  • 2014-10-31
  • 2020-01-14
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
相关资源
最近更新 更多