2016-05-15 21 views
1

如何在string上制作多个preg_match。我做了一项研究,并能够提出以下解决方案。如何制作多个preg_macth

<?php 
$input = '@[email protected] & Good Day ~World~'; 
$regex = '/ 
    ~ 
    (.*?) 
    ~ 
    /six'; 

$input_new = preg_replace($regex,'<i>$1</i>', $input); 
echo $input_new; 

以上将搜索(~)string(~)并更改为斜体格式。我想如何搜索(@)string(@)并更改为加粗格式在同一文本上。

+0

现在你将一个字符串传递给第一个和第二个p arameter。查看手册中的'preg_replace()',看看还有什么可以作为第一个和第二个参数。 – Rizier123

回答

2

preg_replace,因为手册上说,也可以采取多个模式和替代:

<?php 
$input = '@[email protected] & Good Day ~World~'; 
$regexes = array('/~(.*?)~/six', 
       '/@(.*?)@/six' 
       ); 

$replaces = array('<i>$1</i>', 
        '<b>$1</b>' 
       ); 

$input_new = preg_replace($regexes, $replaces, $input); 
echo $input_new; 
+0

谢谢。现在我明白如何去做! – Amran

1

你做你上面做同样的事情,只是这一次改变像这样。否则,只需创建一个函数来做到这一点,像这样:

<?php 

     function transposeBoldItalic($inputString, $embolden="Hello",$italicise="World"){ 
      $result = preg_replace("#(" . preg_quote($embolden) . ")#", "<strong>$1</strong>", $inputString); 
      $result = preg_replace("#(" . preg_quote($italicise) . ")#", "<em>$1</em>", $result); 
      return $result; 
     } 

     // TEST IT: 
     $inputString = "Hello & Good Day World"; 

     var_dump(transposeBoldItalic($inputString, "Hello", "World")); 
     echo(transposeBoldItalic($inputString, "Hello", "World")); 

     // DUMPS 
     <strong>Hello</strong> & Good Day <em>World</em> 

测试它在这里:https://eval.in/571784

+0

谢谢您的详细信息@Poiz – Amran

1

@osnapitzkindle答案是正确的,但你也可以使用preg_replace_callback

echo preg_replace_callback('/([@~])(.*?)([@~])/', function ($matches){ 
    return (strpos($matches[1], '@') !== false) ? "<i>{$matches[2]}</i>" : "<b>{$matches[2]}</b>";}, $input 
    ); 

Ideone Demo

+1

感谢您的回答@Pedro。将期待它 – Amran

+0

你非常欢迎@Amran –