-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHtmlConverter.php
71 lines (65 loc) · 2.01 KB
/
HtmlConverter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
namespace MaxBeckers\HtmlConverter;
/**
* @author Maximilian Beckers <beckers.maximilian@gmail.com>
*/
class HtmlConverter
{
/**
* Format plaintext to html.
*
* @param string $string
* @param bool $force
*
* @return string
*/
public function plainToHtml($string, $force = false)
{
if ($force || false === $this->isHtml($string)) {
// define regex-pattern
$searchRepalce = array(
'#(^|[\n ])([\w]+?://[^ \"\n\r\t<]*)#is' => '\\1<a href="\\2" target="_blank">\\2</a>',
'#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#is' => '\\1<a href="http://\\2" target="_blank">\\2</a>',
'#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i' => '\\1<a href="mailto:\\2@\\3">\\2@\\3</a>',
);
// convert new Line to <br>, make links clickable and return content
return preg_replace(array_keys($searchRepalce), array_values($searchRepalce), nl2br($string));
} else {
return $string;
}
}
/**
* Format html to plaintext.
*
* @param string $string
* @param bool $force
*
* @return string
*/
public function htmlToPlain($string, $force = false)
{
if ($force || true === $this->isHtml($string)) {
$string = preg_replace("/(?:<li>(.+?)<\/li>)/", " - $1\n", $string);
$order = array('<br />', '<br>');
$replace = "\n";
$string = str_replace($order, $replace, $string);
return strip_tags($string);
} else {
return $string;
}
}
/**
* @param string $string
*
* @return bool
*/
private function isHtml($string)
{
preg_match("/<\/?\w+((\s+\w+(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)\/?>/", $string, $matches);
if (count($matches) == 0) {
return false;
} else {
return true;
}
}
}