Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
text.php
1<?php
9
11
12Loc::loadLanguageFile(__FILE__);
13
18class Text
19{
28 public static function replace($template, array $data, $isCut = false)
29 {
30 $from = array();
31 $to = array();
32
33 $dataTmp = array();
34 foreach ($data as $key => $value)
35 {
36 $key = mb_strtolower($key);
37 if (is_array($value))
38 {
39 $value = self::formatArrayToText($value);
40 }
41 else
42 {
43 $value = (string) $value;
44 }
45
46 $dataTmp[$key] = $value;
47 }
48 $data = $dataTmp;
49
50 foreach ($data as $key => $value)
51 {
52 $from[] = '%' . $key . '%';
53 $to[] = $value;
54 }
55
56 $template = str_replace($from, $to, $template);
57
58 if ($isCut)
59 {
60 $template = self::cut($template, $data);
61 }
62
63 return $template;
64 }
65
66 protected static function cut($template, array $data)
67 {
68 $from = array();
69 $to = array();
70
71 $matchResult = preg_match_all('/\%cut\.([A-Za-z0-9_\.]*)\.(start|end)\%/', $template, $matches, PREG_OFFSET_CAPTURE);
72 if (!$matchResult)
73 {
74 return $template;
75 }
76
77 $cut = array();
78 foreach ($matches[0] as $key => $match)
79 {
80 $tag = $match[0];
81 $pos = $match[1];
82 $var = $matches[1][$key][0];
83 $mod = $matches[2][$key][0];
84
85 $from[] = $tag;
86 $to[] = '';
87
88 if (!isset($cut[$var]))
89 {
90 $cut[$var] = array('start' => array(), 'end' => array());
91 }
92
93 if (!isset($cut[$var][$mod]))
94 {
95 continue;
96 }
97
98 if ($mod == 'end')
99 {
100 $pos += strlen($tag);
101 }
102
103 $cut[$var][$mod][] = $pos;
104 }
105
106 $items = array();
107 foreach ($cut as $key => $item)
108 {
109
110 foreach ($item['start'] as $index => $position)
111 {
112 if (!isset($item['end'][$index]))
113 {
114 continue;
115 }
116
117 $sortBy = $item['end'][$index];
118 $items[$sortBy] = array(
119 'key' => $key,
120 'start' => $item['start'][$index],
121 'end' => $item['end'][$index]
122 );
123 }
124 }
125
126 krsort($items);
127 foreach ($items as $item)
128 {
129 if (!empty($data[$item['key']]))
130 {
131 continue;
132 }
133
134 $start = $item['start'];
135 $end = $item['end'];
136 if ($start <= 0 || $end <= 0)
137 {
138 continue;
139 }
140
141 $template = substr($template, 0, $start) . substr($template, $end);
142 }
143
144 return str_replace($from, $to, $template);
145 }
146
153 public static function formatArrayToText(array $list)
154 {
155 $result = array();
156 $num = 0;
157 $count = count($list);
158
159 foreach ($list as $item)
160 {
161 $num++;
162 $isLast = $num >= $count;
163 $result[] = '- ' . $item . ($isLast ? '.': ';');
164 }
165
166 return implode("\n", $result);
167 }
168}
static loadLanguageFile($file, $language=null, $normalize=true)
Definition loc.php:224