Reputation: 9722
I have this simple piece of code to turn *text*
into <strong>text</strong>
.
This all works great, but now I also want to be able to use *
for making lists, like:
* item 1
* item 2
* item 3
This will obviously not work with my current code. Is there a way to change the code so that *
(with a space next to them) are ignored?
This is my current code:
$content = preg_replace('#\*(.*?)\*#is', '<strong>$1</strong>', $content);
EDIT:
Sorry, I might have been a bit unclear with my example.
So this is the original input:
*test*
* test
* test
* test
*test*
This should be formatted as:
<strong>test</strong?
* test
* test
* test
<strong>test</strong>
So bassicly *test*
should show up as <strong>test</strong>
, unless there is a space right next to the *.
So * test
, will remain * test
It's a little like the formatting used in basecamp
Upvotes: 0
Views: 651
Reputation:
You want the inverse of a character class, i.e. [^ ]. I found this invaluable when starting out with regular expressions.
http://www.regular-expressions.info/reference.html
EDIT: I should have put it in your example.
'#[^ ]\*(.*?)\*#is'
EDIT: A tested example after clarification in the comments:
$in = "
*test*
* test
* test
*test*
";
echo preg_replace('/\*([^ \*]+)\*/', '<strong>$1</strong>', $in);
EDIT: Further clarification. When replacing matched characters, like anything between two *'s, it's easier to say 'an asterisk, then anything that isn't an asterisk, followed by a closing asterisk' rather than using a . to match literally the word 'anything' in the plain-english description of what you want. It's also more efficient, having to do with back tracking or something (I'm not sure what the reason is). Since your lists give significance to the trailing spaces I added that to the inverse character class.
Upvotes: 0
Reputation: 2078
You may use [^\s]
to match any non-space character (you could also use\b
to get a word boundary, but you would have issues with non-word characters). Your code would be like this:
$content = preg_replace('#\*([^\s\*]([^\*]*[^\s\*])?)\*#is', '<strong>$1</strong>', $content);
Cheers,
Upvotes: 1
Reputation: 52
Sorry, can i confirm what you are trying to achieve?
You want to change this
* item 1 * item 2 * item 3
into
* <strong>item 1</strong> * <strong>item 2</strong> * <strong>item 3</strong>
Am I correct?
Upvotes: 0