Reputation: 2516
I want to parse a text file, and make the timestamp (if present) colored and bold. Basically, the text could look like this:
15:40 - User1: hey
15:41 - User2: i was about to hit the road, but have at it
15:42 - User1: i was just wondering
Now, I explode on \r\n (which is already stupid because lines may contain a break itself, but leaving that aside for now), so I go through it with a foreach loop.
$string = explode("\r\n", $file);
foreach($string as $ex) {
echo "<p>".$ex."</p>\r\n";
}
Let's say I want to bold the entire timestamp, including username. A str_replace wouldn't work, as : is also in the timestamp. My question is, how do I bold that entire part? A strpos checking for " - " leaves me with offset 5, but how to bold the entire part until the next presence of a colon? (again, leaving aside people may have a colon in their username)
Hell, if I can one up myself, any chance there's a possibility of it changing to $timestamp, $seperator, $user and $message?
Kind regards,
Wesley
Upvotes: 0
Views: 390
Reputation: 76646
You can use strpos()
with an offset
:
foreach($array as $value) {
$needle = ':';
$pos1 = strpos($value, $needle);
$pos2 = strpos($value, $needle, $pos1 + strlen($needle));
$bold = substr($value, 0, $pos2);
$notBold = substr($value, $pos2);
echo "<p><strong>$bold</strong>$notBold</p>";
}
Upvotes: 1
Reputation: 437356
You 'd be much better off using a regular expression here:
$bolded = preg_replace('/^\d+:\d+\s*-\s*[^:]+/', '<b>$1</b>', $ex);
This matches the pattern ^\d+:\d+\s*-\s*[^:]+
and replaces it with <b>$1</b>
, which really means that the match is placed inside bold tags (use <strong>
for more semanticness, this is just an example).
What does ^\d+:\d+\s*-\s*[^:]+
match?
^ at the start of the string...
\d+ one or more digits -+
: a double colon +---> the time
\d+ one or more digits -+
\s* zero or more whitespace
- a dash
\s* zero or more whitespace
[^:]+ one or more of "not :" -----> the username
Upvotes: 1