1 | <?php |
||
9 | class Helpers { |
||
10 | |||
11 | /** |
||
12 | * remove newlines from string and minimize whitespace (multiple whitespace characters replaced by one space) |
||
13 | * useful for cleaning up text retrieved by HtmlPageCrawler::text() (nodeValue of a DOMNode) |
||
14 | * |
||
15 | * @param string $string |
||
16 | * @return string |
||
17 | */ |
||
18 | 1 | public static function trimNewlines($string) |
|
19 | { |
||
20 | 1 | $string = str_replace("\n", ' ', $string); |
|
21 | 1 | $string = str_replace("\r", ' ', $string); |
|
22 | 1 | $string = preg_replace('/\s+/', ' ', $string); |
|
23 | 1 | return trim($string); |
|
24 | } |
||
25 | |||
26 | /** |
||
27 | * Convert CSS string to array |
||
28 | * |
||
29 | * @param string $css list of CSS properties separated by ; |
||
30 | * @return array name=>value pairs of CSS properties |
||
31 | */ |
||
32 | 1 | public static function cssStringToArray($css) |
|
33 | { |
||
34 | 1 | $statements = explode(';', preg_replace('/\s+/s', ' ', $css)); |
|
35 | 1 | $styles = array(); |
|
36 | 1 | foreach ($statements as $statement) { |
|
37 | 1 | $statement = trim($statement); |
|
38 | 1 | if ('' === $statement) { |
|
39 | 1 | continue; |
|
40 | } |
||
41 | 1 | $p = strpos($statement, ':'); |
|
42 | 1 | if ($p <= 0) { |
|
43 | 1 | continue; |
|
44 | } // invalid statement, just ignore it |
||
45 | 1 | $key = trim(substr($statement, 0, $p)); |
|
46 | 1 | $value = trim(substr($statement, $p + 1)); |
|
47 | 1 | $styles[$key] = $value; |
|
48 | 1 | } |
|
49 | 1 | return $styles; |
|
50 | } |
||
51 | |||
52 | /** |
||
53 | * Convert CSS name->value array to string |
||
54 | * |
||
55 | * @param array $array name=>value pairs of CSS properties |
||
56 | * @return string list of CSS properties separated by ; |
||
57 | */ |
||
58 | 1 | public static function cssArrayToString($array) |
|
59 | { |
||
60 | 1 | $styles = ''; |
|
61 | 1 | foreach ($array as $key => $value) { |
|
62 | 1 | $styles .= $key . ': ' . $value . ';'; |
|
63 | 1 | } |
|
64 | 1 | return $styles; |
|
65 | } |
||
66 | |||
67 | /** |
||
68 | * Helper function for getting a body element |
||
69 | * from an HTML fragment |
||
70 | * |
||
71 | * @param string $html A fragment of HTML code |
||
72 | * @param string $charset |
||
73 | * @return \DOMNode The body node containing child nodes created from the HTML fragment |
||
74 | */ |
||
75 | 15 | public static function getBodyNodeFromHtmlFragment($html, $charset = 'UTF-8') |
|
94 | } |
||
95 |
If you suppress an error, we recommend checking for the error condition explicitly: