开发者

specific string formatting in php

I have a series of strings in the following format.

temp_low_warning

I am using this code to produce

Warning, Temp Low!

$st开发者_如何学编程r = "temp_low_warning";
$parts = explode("_",$str);
$return = ucfirst($parts[2]) . ", " . ucfirst($parts[0]) . " " . ucfirst($parts[1]) . "!";

Is there a better way to do this using regular expressions? I'm more concerned about performance; this script is running as part of a cron job that executes quite frequently.

So I guess my first question is:

Can this be done using Regular Expressions?

Second question:

Should this be done using Regular Expressions?


  1. Yes, matching texts with a fixed number of delimiters is quite doable. /(\w*)_(\w*)_(\w*)/ is one example that fits your example.
  2. No, the meaning of the explode is very clear in your example. You don't need the expressibility of full pattern matching here.

Performance is quite likely not of concern here as your cron-job needs to fire up php for every invocation. The regexp vs. explode difference will not be noticable.


I would leave your code as is.

If you absolutely want to refactor it I would apply the capitalization to the $parts to make clear that it applies to all the array items.

$str = "temp_low_warning";
$parts = array_map('ucfirst',explode("_",$str));
$return = $parts[2] . ", " . $parts[0] . " " . $parts[1] . "!";

And I would stay away from regular expression to do similar tasks, as advised into the php online reference itself (performance and clarity issues)


That code took 0.0003 seconds to run on my machine. Are you sure you need to optimize it any further?

As to your questions, the answers are no and no.


Without capitalization:

preg_replace("/(\w+)_(\w+)_(\w+)/", "$3, $1 $2!", $string)

I'm not sure if there's an easy way to capitalize, though.

If this command is executed really frequently in a loop, then there may be a slight improvement in performance when using regex. However, with such short strings it shouldn't be that important.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜