How can I parse in PHP to format user-submitted posts? - php

I want to give users some formatting options like Reddit or stackOverFlow do, but want to keep it in PHP. How can parse a string in PHP such that it recognizes patterns like **[anything here]**?
explode() doesn't seem to solve the problem as elegantly as I'd like. Should I just use nested ifs and fors based on explode()'s output? Is there a better solution here?

This has already been done countless times by others, I'd recommend using existing libraries.
For example, you can use Markdown: http://michelf.com/projects/php-markdown/

Check regular expressions:
$string = '*bold* or _underscored_ or even /italic/ ..';
// italic
$string = preg_replace('~/([^/]+)/~', '<i>$1</i>', $string);
// bold
$string = preg_replace('/\*([^\*]+)\*/', '<b>$1</b>', $string);
// underscore
$string = preg_replace('/_([^_]+)_/', '<u>$1</u>', $string);
echo $string;
output:
<b>bold</b> or <u>underscored</u> or even <i>italic</i> ..
or use a BBCode parser.

Related

php - Replace Template Code with HTML

I got a Button, that creates this template code
[5afc4076e9f1b1526481014.pdf]##LINKNAME## (96.51 kb)
The filename and file size vary und the user can change the ##LINKNAME##, as well.
This code goes to a database and when I get it back, I want to replace it to
##LINKNAME## <i>(96.51 kb)</i>
I think I need to use preg_replace() but I am not really good at regular expressions.
I stopped here:
<?php
$string = ' [5afc4076e9f1b1526481014.pdf]##LINKNAME## (96.51 kb)';
$regex = '[[a-zA-Z0-9]+.pdf](.*?)\s';
$replace = 'I DONT KNOW';
echo preg_replace($regex, $replace, $string);
?>
I know that this is a complete mess, but I'm not getting any results as long as I don't know the regex and the correct $replace.
Regex: ^\[([^\]]+)\](\w+)\s\(([^)]+)\)$
Replace with: \2<i>(\3)</i>
Demo

I want to delete some tags in a document using PHP

How can I mass delete tags like these in a document using PHP preg_replace?
<text:alphabetical-index-mark-start text:id="IMark169843024"/>
The only thing that is different from one to another is the number after IMark.
Thank you!
This is something you can fine-tune to whatever you need. But in general terms you can do something like this:
$string = preg_replace('~<text:.*?>~', '', $string);
Demo
Or you can filter it all the way down with something like this:
$string = preg_replace('~<text:alphabetical-index-mark-start text:id="IMark\d{9}"/>~', '', $string);
Demo
Either way, it'll be pretty easy to strip these tags out.

preg_match (I can't do regex)

The company I work for have asked me to give them the ability to place a modal box on the web page from the CMS, but do not want to type HTML. As I cannot for the life of me understand regex I can't get it.
The layout of the code they should type is this:
++modal++
Some paragraph text.
Another paragraph.
++endmodal++
The paragraphs are already converted by markdown into <p>paragraph</p>.
So really the match has to be ++modal++ any number of A-Za-z0-9any symbol excluding + ++endmodal++ then replaced with HTML.
I'm not sure it preg_match or preg_replace should be used.
I got this far:
$string = '++modal++<p>Hello</p>++endmodal++';
$pattern = '/\+\+modal\+\+/';
preg_match($pattern, $string, $matches);
Thank you in advance.
EDIT: A to be a bit more clear, I wish to replace the ++modal++ and ++endmodal++ with HTML and leave the middle bit as is.
I don't really think you need a RegEx here as your delimiters remain always the same and always on the same position of the string. Regular expressions are also expensive on resources and as a third counter argument you said you're not fit with them.
So why not use a simple replacement or string trimming if it comes to that.
$search = array('++modal++', '++endmodal++');
$replacement = array('<tag>', '</tag>');
$str = '++modal++<p>Hello</p>++endmodal++';
$result = str_replace($search, $replacement, $str);
Where, of course, '<tag>' and '</tag>' are just example placeholders for your replacement.
This is what the manual for str_replace() says:
If you don't need fancy replacing rules (like regular expressions),
you should always use this function instead of preg_replace().
I think you should get your desired content using:
preg_match('/\+\+modal\+\+([^\+]+)\+\+endmodal\+\+/', $string, $matches)
$matches[1] = '<p>Hello</p>
You're trying to re-invent the wheel here. You're trying to write a simple template system here, but there are dozens of templating tools for PHP that you could use, ranging from big and complex like Smarty and Twig to really simple ones that aren't much more than you're trying to write.
I haven't used them all, so rather than recommend one I'll point you to a list of template engines you could try. You'll probably find more with a quick bit of googling.
If you do insist on writing your own, it's important to consider security. If you're outputting anything that contains data entered by your users, you must make sure all your output is properly escaped and sanitised for display on a web page; there a numerous common hacks that can take advantage of an insecure templating system to completely compromise a site.
<?php
$string = '++modal++<p>Hello</p>++endmodal++';
$patterns = array();
$patterns[0] = "/\+\+modal\+\+/"; // put '\' just before +
$patterns[1] = "/\+\+endmodal\+\+/";
$replacements = array();
$replacements[1] = '<html>';
$replacements[0] = '</html>';
echo preg_replace($patterns, $replacements, $string);
?>
Very similar to this example

Replace smileys inside [code][/code] tags

So I started a post before but it got closed :( since then I have managed to progress a little realizing I need to somehow grab the content inside the [code][/code] tags and do a str_replace() on the smiley bbcode text within them, here is what I have so far but its not working
if (preg_match_all('~[code](.*?)[\/code]~i', $row['message'], $match)){
foreach($match[1] AS $key) {
$find = array(':)',':(',':P',':D',':O',';)','B)',':confused:',':mad:',':redface:',':rolleyes:',':unsure:');
$replace = array(':)',':(',':P',':D',':O',';)','B)',':confused:',':mad:',':redface:',':rolleyes:',':unsure:');
}
$message = str_replace($find, $replace, $key);
} else {
$message = $row['message'];
}
it just returns no message content at all.
if i change this line:
$message = str_replace($find, $replace, $key);
to this:
$message = str_replace($find, $replace, $row['message']);
it sort of works but replaces all smileys inside the whole message rather then just the content inside the [code][/code] tags which I assume is being represented by $key?! ...any help please its causing my brain to overload!
I did find this question which is different but very relevant to mine but there was no real answer to it.
I think it might be easier for you to use an existing BBCode parser (eg. NBBC) or at least checking how they did that. And they did it in a much more intelligent way. Rather than using regexp, they use a lexer, which splits it into separate tags (shown below). Then, they just don’t do anything to a [code] tag. If you still want to stay with your solution, I would, for one, split them out to arrays (bbcode = explode('[code]', bbcode) and then the same for [code]. Every second list element should not have other parsing used. As stated before: there is no purpose in reinventing the wheel, so don’t do that.
This is how their solution works:
[b]Hello![/b]
[code]
#/usr/bin/python
import antigravity
[/code]
Python is much more awesome.
Becomes eg. an array with the following elements:
[b]Hello![/b]
[code]…[/code]
Python is much more awesome.
And then it applies the formatting it should apply. Much better and more human.
not a comment due to length.

Find content inside square brackets with PHP and replace (regex?)

I need to convert this:
[video=http://example.com/video.flv]
Into this:
Using PHP - probably regex. A string can contain many of these 'code blocks' and I need to give each video a unique ID. How can I do this? I am sorry, I really don't know much about regex.
Well if they are all standard in their format, why not just use str_replace()?
$s = '[video=http://www.site.com/video.flv]';
$url = str_replace(array('[video=',']'),array('',''),$s);
echo 'click me!';
$cnt = 0;
preg_replace('/\[.*?=(.*?)]/e', '$1', $text);
not tested, will probably blow up and steal your dog, etc...

Categories