PHP:替换字符串中的单词

时间:2015-05-18 12:57:42

标签: php regex preg-replace

我有以下字符串:

<div class="quick-quote">
<h3>Quick Quote!</h3>
<form class="cm-ajax" action="index.php" method="post" id="quick_quote_form"> 
<div id="quick-quote">
<div class="clearfix">
<label style="width:73px;" >Width:</label>
</div>

<div class="input">
<input type="text" placeholder="enter width" name="d_width" id="d_width" class="required form-control" >
</div>
<div class="clearfix">
<label style="width:73px;" >Height:</label>
</div>
<input type="submit" class="get-quote-btn" value="Get Quote" name="dispatch[get_qoute.get_rates]" /> 
 </div>
 <div class="result"></div>
 <!-- tag -->
 <input type="hidden" name="result_ids" value="result" />
 </form>
 </div>
 Controller code:
   <?php
  use Tygh\Registry;
  if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if ($mode == 'get_rates') {
  $height= $_POST["d_height"];
  $width=$_POST["d_width"];
  $val = $height+$width;
  Registry::get('view'); 
  Registry::get('ajax')->assign('get_rates', $val);
 } 
 exit;
 }
 ?>
  Result set is coming correctly , Now I don't know how to show response in block div.
 <div class="result"></div>
 <!-- tag -->
 <input type="hidden" name="result_ids" value="result" />
  Thanks in advance. 

现在我想将@ c24-green的定义替换为#fff。

我试过了:

@c24-blue: #005ea8; @c24-green: #737948;

结果应为:

$string = '@c24-blue: #005ea8; @c24-green: #737948;';
$string = preg_replace('/([@c24-green:]) (.*);/', '$1' . ' #fff;', $string);

是否有解决方案让这个工作?

此致 启

2 个答案:

答案 0 :(得分:1)

怎么样:

$string = preg_replace('/(@c24-green:)[^;]+/', '$1 #fff', $string);

答案 1 :(得分:1)

从字符类中删除字符串"@c24-green:",以下应该可以工作..

(@c24-green:) (.*);
 ^         ^

$string = preg_replace('/(@c24-green:) (.*);/', '$1' . ' #fff;', $string);

请参阅DEMO

修改:如果您想将其设为通用..您可以使用以下内容:

(@[^:]*:) ([^;]*);

请参阅DEMO