tags:

views:

26

answers:

3

I'm trying add a bold/strong tag the line headings of the follow string/text block:

Length Determination: the dimensions above show what center-to-center length can be achieved by the connecting linkage length shown for male spherical rod ends.

Material: aluminum.

Specials: specials are available at any volume.

Standards: MCP offers

But I can't get the regex to include multiple words. Here's my result:

Length Determination: the dimensions above show what center-to-center length can be achieved by the connecting linkage length shown for male spherical rod ends.

Material: aluminum.

Specials: specials are available at any volume.

Standards: MCP offers

Notice the word "Length" in "Length Determination" isn't bold/strong. That needs to be included. Can someone give me a quick hand?

My code:

$str = preg_replace_callback("/([^\s]+:)/i", 'makeStrong', $str);

function makeStrong($matches) {
    return "<strong>" . $matches[0] . "</strong>"; 
}
A: 

Try this:

<?
$str = "
Length Determination: the dimensions above show what center-to-center length can be achieved by the connecting linkage length shown for male spherical rod ends.
Material: aluminum.
Specials: specials are available at any volume.
Standards: MCP offers
";

$str = preg_replace_callback("/^([\w ]+:)/mi", 'makeStrong', $str);

function makeStrong($matches) {
    return "<strong>" . $matches[0] . "</strong>"; 
}

print $str;
?>

Your method is failing because [^\s] matches "not whitespace" - meaning it won't match the spaces between words.

EDIT Fixed

Jamie Wong
Tested. Doesn't work.
gurun8
Fixed: see edit. Forget the `m` multiline modifier
Jamie Wong
A: 

Your [^\s] character class is matching anything that's not whitespace - which obviously means that it won't match across words that have whitespace between them. Try this instead:

$str = preg_replace_callback("/^([\w\s]+?:)/i", 'makeStrong', $str);
Amber
This does work in combo with my original:preg_replace_callback("/^([\w\s]+?:)|([^\s]+:)/i", 'makeStrong', $str);
gurun8
A: 

What about this:

$str = preg_replace_callback("/([ \w]+:)/", 'makeStrong', $str);

If the pattern starts with ^, it will only match something found in the beginning of the whole string (to me your question sounded like you wanted to process a multi-line string in one pass).

If \s is used together with the \w, it will match line breaks too and include them within the <strong />, as you probably noticed.

Lauri Lehtinen
BINGO! You nailed it and super small. Well played.
gurun8