一个非常 糟糕的解决方案:
$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