开发者

Regex fix for preg_replace_callback function

开发者 https://www.devze.com 2023-04-04 10:47 出处:网络
STRING : $string = \'{$string#anything#something this string will output default |ucfirst|strtoupper}\';

STRING :

$string = '{$string#anything#something this string will output default |ucfirst|strtoupper}';

PREG_REPLACE_CALLBACK CODE(PHP) :

$string = preg_replace_callback('/\{\$?([^# ]+)\#?([^ ]+)? ?([^|]+)?[ \|]?([^\}]+)?\}/', $matches, $string);

OUTPUT($matches) :

Array
(
    [0] => {$string#anything#something can you hear me? |ucfirst|ucfirst|ucfirst|strtoupper}
    [1] => string
    [2] => anything#something
    [3] => can you hear me? 
    [4] => ucfirst|strtoupper
)

开发者_开发技巧REQUIREMENT : in place of {$string this string will output default |ucfirst|strtoupper}, i want to use {$string this string will output default ucfirst|strtoupper}(notice:pipe sign in front of ucfirst is removed);

IMPORTANT : output(ie $matches array) should look same as printed above.

Your help will be much appreciated, thanks for reading.


I tried your code with changing your function...

The code

 <pre>
 <?php
      $string = '{$string#anything#something this string will output default |ucfirst|strtoupper}'; http://www.magentocommerce.com/support/magento_core_api 
      preg_match('/\{\$?([^# ]+)\#?([^ ]+)? ?([^|]+)?[ \|]?([^\}]+)?\}/', $string, $matches);
      var_dump($matches);
  ?>
  </pre>

Result obtained

array(5) {
    [0]=>string(80) "{$string#anything#something this string will output default |ucfirst|strtoupper}"
    [1]=>string(6) "string"
    [2]=>string(18) "anything#something"
    [3]=>string(32) "this string will output default "
   http://php.net/manual/en/function.preg-replace-callback.php [4]=>string(18) "ucfirst|strtoupper"
}

Is it conform to your expectation ? Should we replace "this string will output" default by "can you hear me? " you want to remove to the pipe before ucfirst do you want to do this in the string and update the reg exp in consequence, if it so what is the rule to identify ''ucfirst'' string (the last string before the first pipe?)

What are you trying to do with the preg_replace_callback this function will call a function (your $matches parameter) for each motif found... Is it your idea?

Linked documentation: http://php.net/manual/en/function.preg-replace-callback.php

0

精彩评论

暂无评论...
验证码 换一张
取 消