Я новичок в PHP, и мне нужно вырезать строку в определенные разделы на основе значения, а не числа символов.
Я слышал о функции взрыва и подстроке, но я не знаю, как использовать ее для достижения того, что я хочу.
У меня есть строка вывода: Name: example Email: [email protected] Website: http://examples.com/Comment: this is where the comment goes, we can't use explode because there lots of spaces here Another comment: this is another comment Some random info: this is more info...
Я хочу отображать эту информацию в отдельных строках для эстетических целей.
Есть ли способ вернуть слово после определенного слова, но перед другим конкретным словом?
Вы можете использовать регулярные выражения для достижения этой цели, если заданная строка всегда находится в обычном формате.
Использование preg_split()
может стать основой:
$arr = preg_split('/(?=[A-Z])/', $str, -1, PREG_SPLIT_NO_EMPTY);
Регулярное выражение разбивает заданную строку в точке непосредственно перед любой прописной буквой, используя положительное утверждение.
Если мы сделаем print_r()
в массиве, вы увидите следующий вывод:
Array
(
[0] => Name: example
[1] => Email: [email protected]
[2] => Website: http://examples.com/
[3] => Comment: this is where the comment goes ...
[4] => Another comment: this is another comment
[5] => Some random info: this is more info...
)
Как вы получаете эту строку в первую очередь? Если это что-то под вашим контролем, то я настоятельно рекомендую использовать JSON или подобное для передачи данных. Это проще и менее глючит - и вы можете быть уверены, что он работает.
Это работает -
$regex = "/[A-Z][^A-Z]*?\:\s.*?(?(?=[A-Z][^A-Z]*?\:)|$)/";
$string = "Name: Example Email: [email protected] Website: http://examples.com/ Comment: this is where the comment goes, we can't use explode Because there Lots of spaces here Another comment: this is another comment Some random info: this is more info";
if(preg_match_all($regex, $string, $matches)){
var_dump($matches[0]);
}
/*
OUTPUT
array
0 => string 'Name: Example ' (length=14)
1 => string 'Email: [email protected] ' (length=23)
2 => string 'Website: http://examples.com/ ' (length=30)
3 => string 'Comment: this is where the comment goes, we can't use explode Because there Lots of spaces here ' (length=98)
4 => string 'Another comment: this is another comment ' (length=41)
5 => string 'Some random info: this is more info' (length=35)
*/
Вы можете разделить на большую букву, предполагая, что ваши названия всегда начинаются с одного.
$text = "Name: example Email: [email protected] Website: http://examples.com/ Comment: this is where the comment goes, we can't use explode because there lots of spaces here Another comment: this is another comment Some random info: this is more info...";
$test = preg_split('/(?=[A-Z])/', $text);
foreach($test AS $line){
echo $line."<br />";
}
Используйте простые функции манипуляции строками, подобные этому, и сделайте жизнь ur простой.
<?php
$strx='Name: example Email: [email protected] Website: http://example.com/';
$str=stristr($strx,"Comment :",true);// Take all chars before 'Comments :'
$str= str_replace(": ",":",str);
$str = str_replace(" ","\n");
echo $str . '\n Comment : '. ; // Its
echo stristr($strx,"Comment :"); // Done
?>
Как правило, функция explode()
- это то, что вы ищете, но это не будет работать слишком хорошо на вашем примере, поскольку вам не хватает уникальных символов для разделения. Что-то вроде:
Name: example; Email: [email protected]; Website: http://example.com/
Например, вы можете взорвать строку точкой с запятой. explode()
explode()
не будет работать для этого случая. Вместо этого вы можете использовать preg_split()
. Посмотрите на мой ответ .
Вот REGEX, который вытащит каждую часть, которую вы просите:
<?php
$string = "Name: example Email: [email protected] Website: http://examples.com/ Comment: this is where the comment goes, we can't use explode because there lots of spaces here Another comment: this is another comment Some random info: this is more info... ";
$name = '';
$email = '';
$website = '';
if (preg_match('/^Name: ([-A-Z \'.]+) Email: ([-A-Z0-9_@.]+) Website: ([-A-Z0-9\/.:]+) /i', $string, $matches)) {
$name = $matches[1];
$email = $matches[2];
$website = $matches[3];
}
print '
Name: '.$name.'
Email: '.$email.'
Website: '.$website;
Comment:
так что если вам нужно соответствующим образом настроить RegExp (терминатор строки после того, как веб-сайт убьет его) - но в противном случае, да, если вам нужно манипулировать строками, нет ничего лучше или более гибкий, чем регулярные выражения IMO.