0

I want to bold everything in a string that comes before a : and do it the following way (PHP):

$string = preg_replace('/(.*):/', '<span class="bold">\\1:</span>', $string);

Now I need an exception: I do NOT want to bold the text if there is a ( before the :. Is this possible?

(So basically Size: 123 should get bolded, but We increase this (Max: 30) should NOT get bolded)

1
  • 1
    <img alt="Foo:bar" /> Now what? // Even better: <a href="http://example.com"><img src="http://example.com/image.png"/></a> :) Commented Feb 21, 2013 at 12:33

3 Answers 3

2

Sure, just use :

$string = preg_replace('/([^(]*):/', '<span class="bold">\\1:</span>', $string);

It will match any character before the : except (.

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

1 Comment

That's great, thank you. If I would now want to NOT bold the Max: from the original example at all, how would I do that (since currently "Max:" gets bolded)
0

You are going to break ... lets say: Everything

<a href="http://example.com"><img src="http://example.com/image.png"/></a>

Now what?

I assume, that this Size: 123 is not "somewhere" on the page. So format it, when you output it

list($name, $value) = array_map('trim', explode(':', $attribute));
echo "<span class=\"bold\">$name</span>: $value";

It would also be better to have this as array in the first place like in array('Size'=>'123')

2 Comments

Nothing is going to break, html is not allowed in that place. Also this is used for outputting only, not for storing. The data is stored properly, for this kind of text I can't have a structure like "size -> 30" because the attributes are different for each dataset.
@user2015253 That doesn't explain, why you can't use arrays instead of plain-text strings (array('fooName' => 'barValue'))
0

@blue112 is almost there but in order not do bold Max in the string We increase this (Max: 30) one needs to make sure that the whole string doesn't contain any opening brackets. This is done by adding the beginning-of-string marker ^:

$string = preg_replace('/^([^(]*):/', '<span class="bold">\\1:</span>', $string);

See it in action here.

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.