且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用更好的替换引号字符

更新时间:2023-12-05 13:38:58

我可能会在这里丢失一些明显的东西,但我认为以下RegEx解决方案可以工作 -

  subject ='testabctestabc'; 
result = subject.replace(/([A-Za-z ] *)/ ig,& ldquo; $ 1& rdquo;);
alert(result );

如果您使用的是PHP,那么您可以在PHP中编写一些类似的代码 - (我的PHP技能虽然有点缺乏!下面的代码是用RegEx Buddy生成的,所以它没有经过测试,可能需要更改)

  $ subject ='test abctestabc'; 
$ result = preg_replace('/([A-Za-z] *)/ i','& ldquo; $ 1& rdquo;',$ subject);

或者,您可以使用PHP将内容加载到DIV中,然后使用JavaScript更改DIV内容,这里有一些JQuery可以完成这项工作 -

  $(#contentdiv)。text($(#contentdiv ).text()。replace(/([A-Za-z] *)/ ig,& ldquo; $ 1& rdquo;)); 

有一个jsfiddle演示上面的jQuery here


I have a webpage where I want to replace all standard quote characters " with the nicer looking quotes. For example, we have

"hello world"

which would be replaced with

“hello world”

in markup, showing the much better looking 'curly' quotes.

The two HTML special characters are pairs, in that they "open" and "close" a quote block, instead of being a generic double dash, which is where I'm struggling - simply replacing all quotes with “ is easy, but I want to do it so the open/close pairs are respected.

I might be missing something obvious here, but I think the following RegEx solution would work -

subject = 'test "abc" test "abc"';
result = subject.replace(/"([A-Za-z ]*)"/ig, "“$1”");
alert(result);

If you were using PHP then you could write some similar code in PHP - (my PHP skills are somewhat lacking though! The code below was generated with RegEx Buddy so it hasn't been tested and may need changing)

$subject = 'test "abc" test "abc"';    
$result = preg_replace('/"([A-Za-z ]*)"/i', '“$1”', $subject);

Alternatively, you could load the content into a DIV using PHP then use JavaScript to change the DIV contents, here's a bit of JQuery that would do the job -

$("#contentdiv").text($("#contentdiv").text().replace(/"([A-Za-z ]*)"/ig, "“$1”"));

There's a jsfiddle that demonstrates the above JQuery here.