1

I have a series of strings in the following format.

temp_low_warning

I am using this code to produce

Warning, Temp Low!

$str = "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?

2
  • If performance is really an issue, I wouldn't use PHP to do this. Commented Sep 13, 2011 at 13:40
  • i dont think use Regular Expressions will better than you code. Commented Sep 13, 2011 at 13:44

4 Answers 4

3
  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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.