Daniel Szalay
Daniel Szalay

Reputation: 4101

Replacing first word of every line in PHP

My html view displays contents of an .htgroup file on screen, for example:

download: user1 user2 user3
movies: test test2 user1 user2 user3

I want to encapsulate the group names (download and movies) in <strong> tags, so that they appear bold in the browser. How can I do this in PHP5? I'm sure there is an elegant way to do this with a function like preg_replace(), but I'm very bad at regex.

Line separator is \n.

Upvotes: 0

Views: 270

Answers (4)

Lorenzo Marcon
Lorenzo Marcon

Reputation: 8169

Assuming that every row is separated by a \n, an elegant regex solution would be:

$str = "download: user1 user2 user3\n".
"movies: test test2 user1 user2 user3";

$rows = explode( "\n", $str );
foreach( $rows as $r ){
    echo preg_replace('/^([^ ]*):/', '<strong>$1</strong>:', $r);
}

Then probably you'd like to add a line break after every row, if you want to use a html(-ish) layout. But I leave to you the presentation part.

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71384

I don't think there is need for regex. Something like this should easily do the trick

$lines = file('/path/to/.htgroup');

foreach($lines as $line) {
    echo '<strong>' . str_replace(':', ':</strong>', $line) . '<br />';
}

Note the addition of a line break to preserve the output on different lines in the browser.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

You gave no specifics about how the text is formatted, so maybe this?

$htgroup = preg_replace('/^.*?:/m', '<strong>\0</strong>', $htgroup);

Upvotes: 2

slugonamission
slugonamission

Reputation: 9642

You can cheat and do it with str_replace in this case, like $line = "<strong>".str_replace(":", ":</strong>", $line);, but the non-messy and reliable way is to use regex.

Upvotes: 8

Related Questions