PHP-Regex.将引号中的任何空格替换为下划线


PHP - Regex. Replace any space in quote with underscore?

regex noob-hear。通过PHP和preg_replace()。。。

我正在努力做这个。

id="New York State"

进入这个。

id="New_York_State"

但不是这样。

id="New_York_State"_class="United_States"


我所有的尝试都很糟糕!
我已经阅读了一些教程,但在用正确的语法构建有用的模式时仍然遇到了很多困难。

请,请,请在你的答案中包括正则表达式模式的解释!此外,如果您觉得可以,请提供好的PHP正则表达式教程或文章的任何链接。谢谢

使用SimpleXMLElement

header('Content-Type:text/plain');
$xml = simplexml_load_file('log.svg', "SimpleXMLElement");
recursiveReplace($xml);
echo $xml->asXML();

使用的功能

function recursiveReplace(&$xml) {
    foreach($xml as $k => $value) {
        foreach($xml->attributes() as $n => $d) {
            $xml[$n] = preg_replace('/'s+/', '_', $d);
        }
        recursiveReplace($value);
    }
}

一个极其糟糕的解决方案:

$string = 'blabla id="New_York_State" class="United_States" blabla';
$new_string = preg_replace_callback('#'"([^"]*)'"#', function($m){
    return('"'. str_replace(' ', '_', $m[1]) .'"');
}, $string);
echo $new_string;

输出:

blabla id="New_York_State" class="United_States" blabla

双引号后面只允许使用id=class=

$string = 'blabla id="New_York_State" class="United_States" blabla "this won''t get underscored" yaaaay';
$new_string = preg_replace_callback('#(?<=id=|class=)'"([^"]*)'"#', function($m){
    return('"'. str_replace(' ', '_', $m[1]) .'"');
}, $string);
echo $new_string;

输出:

blabla id="New_York_State" class="United_States" blabla "this won't get underscored" yaaaay

有一个名为str_replace的函数。

你的代码是这样的:

$id=str_replace(","_",$id(;或更好的$id=str_replace("纽约州","New_York_State",$id(;

来源:http://php.net/manual/en/function.str-replace.php