массивы — PHP возвращает список всех переменных в тексте, которые соответствуют шаблону

У меня есть текст, например, так:

Lorem Ipsum% final_walk_through_date% — просто фиктивный текст
полиграфия и набор текста. % customer_full_name% Lorem Ipsum имеет
был стандартным фиктивным текстом в отрасли с 1500-х годов, когда
неизвестный принтер взял камбуз типа и взломал его, чтобы сделать тип
книга образцов. Он пережил не только пять веков, но и
прыжок в электронный набор текста, оставаясь практически без изменений. Это
был популяризирован в 1960-х годах с выпуском листов Letraset
содержащие отрывки Lorem Ipsum, а в последнее время и с рабочим столом
издательское программное обеспечение, такое как Aldus PageMaker, включая версии Lorem
Ipsum% shopping_side_commission_percent%. % Escrow_officer_first_name%
и% ccrs_date%.

Я хочу использовать PHP для сканирования этого текста и поиска любой переменной, имеющей этот шаблон% variable_name%, а затем добавить это значение в массив.

В итоге у меня будет массив, который выглядит так:

array[
'%final_walk_through_date%',
'%buyer_full_name%',
'%buying_side_commission_percent%',
'%escrow_officer_first_name%',
'%ccrs_date%'
]

Как это можно сделать?

0

Решение

Вы могли бы использовать preg_match_all() :

preg_match_all('~%\w+%~', $text, $matches);
print_r($matches[0]);

Выходы:

Array
(
[0] => %final_walk_through_date%
[1] => %buyer_full_name%
[2] => %buying_side_commission_percent%
[3] => %escrow_officer_first_name%
[4] => %ccrs_date%
)
3

Другие решения

Это в основном именно то, что preg_match_all для:

$s = "Lorem Ipsum %final_walk_through_date% is simply dummy text of the printing and typesetting industry. %buyer_full_name% Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum %buying_side_commission_percent%. %escrow_officer_first_name% and %ccrs_date%.";

preg_match_all('/%[^%]*%/', $s, $matches);

var_dump($matches);

https://3v4l.org/Rvc5n

2

Это можно сделать и без регулярных выражений.
Вы можете использовать разнесение и разнесение на%, а элементы массива с пробелами не переменные.

$str = "Lorem Ipsum %final_walk_through_date% is simply dummy text of the printing and typesetting industry. %buyer_full_name% Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum %buying_side_commission_percent%. %escrow_officer_first_name% and %ccrs_date%.";
$arr = explode("%", $str . " ");
// Adding space to end of string to make sure it removes last part if it's not a variable
$newArr = array_filter($arr, function($v){
If(strpos($v, " ") === false) return $v;
});

var_dump($newArr);

Если вам нужно сбросить индекс массива, вы можете использовать array_values, чтобы он снова считался с 0.

https://3v4l.org/909Zd



Mickmackusa версия этого:

$str = "%start_of_input% Lorem Ipsum %final_walk_through_date% is simply dummy text of the printing and typesetting industry. %buyer_full_name% Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum %buying_side_commission_percent%. %escrow_officer_first_name% and %ccrs_date%.";
$arr = explode("%", " " . $str . " ");
$newArr = array_filter($arr, function($v){
return strpos($v, " ")===false ? true : false;
});

var_dump($newArr);
1
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector