I've been trying to impliment a BBCode type system into my news script. However, php.net's explanation of preg_replace is quite horrible. Can anyone here explain it more simple?
Announcement
Collapse
No announcement yet.
preg_replace()
Collapse
X
-
Regular Expressions
preg_replace() is a function that will replace stuff in a string with help of regular expressions. Here is a little example of this:
PHP Code:// declare our little string
$string = '{u}This is a {b}string{/b} that {i}contains{/i} some commands..{/u} :)';
// replace all the commands using Regular Expressions
$string = preg_replace("/\{(\/)?(b|i|u)\}/i","<\\1\\2>",$string);
// print the modified string
print($string);
The RegExp begins with a / which is a delimiter which tells the function where the expression begins and where it ends. You can use almost any alphanumeric character, but my favourite is the /.
The next step is to begin the tag which begins with a { but since it's a special character in a RegExp then we'll have to escape it like this: \{.
The next pieces of characters is (\/)? and it checks if the current tag is a closing or opening tag. Since we're using the / character as a delimiter then we'll have to escape it like this: \/. The reason to why it's inside ( and ) is that we want to save it, I'll come to that later.
Now it's time to get the current tag. In the next piece, (b|i|u), you can see that I'm using the | character. In a RegExp the | character means or, in other words, this piece of code means if the char is b or i or u.... We have this piece inside ( and ) since we want to use it later.
Then we've got to close the tag again, and we also have to escape the } character since it's also a special character in a RegExp.
Then we end the RegExp by adding a / and the i after the delimiter means that this is an irregular search, which means that it doesn't matter if the tags are in lower- or uppercase.
The second argument of the function is the piece of code that should replace the piece found in the string. Since we want to convert it to HTML then we'll start it by the starting character <. \\1 means the stuff that was found inside the first ( and ), which means that in this case it would contain a / if the found tag was a closing tag, otherwise it's empty. \\2 contains the type of the tag, which means it will contain b,i or u. Then we close the HTML-tag with a >.
I hope that this makes some sense to you...
-
I'm doing this for a free news engine (ZNews), so I don't know who will be using it.
There's one thing missing though. The way you did it, people can have opening {B}s but no closing {/B}s. How would I set it up to have {B}anything{/B}whatever
BTW, You guys have to get rid of this Tab = 3 spaces thing. I hate having to use my mouse to kick the Post Reply button.Last edited by Xelopheris; Sun 31 Aug '03, 6:39am.
Comment
widgetinstance 262 (Related Topics) skipped due to lack of content & hide_module_if_empty option.
Comment