2016-08-18 10 views
1

Я ищу PHP решения, у меня есть некоторые содержимое HTML с некоторыми пользовательскими тегами, какКак найти пользовательский тег внутри текста в PHP

$html = "he approaches very silently towards him but at the last point of time, the man gets the hint and manages to escape from the attack. , 
[vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [/vid] What happens in the latter is just breath-taking and comes with a reason why this video has gone viral in such short span of time"; 

Я хочу Вывода только чуть ниже упоминание текста:

[vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [/vid] 

    or 
[vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [Endvid] 

$ FWithReplaceWord будет YouTube "V =" ID eED6VRcj1Rs

Нужна

OUTPUT
<div class='embed-responsive embed-responsive-16by9 vid1'><iframe class='embed-responsive-item' src='//www.youtube.com/embed/$FWithReplaceWord' allowfullscreen></iframe></div> 

Я использую

preg_match_all('~([vid](.*?)[/vid])~', $html, $matches); 

Но ее не работает. Пожалуйста, помогите мне.

+0

Вы желающей массив? – Blakethepatton

+0

Если вы хотите только «[vid]» в '[vid class =" vid1 "]' почему вы не используете простую 'str_replace', вам не нужно описывать все до закрывающего тега? –

+0

@CasimiretHippolyte хочет преобразовать этот текст в

, так что хотите v = значение eED6VRcj1Rs от url вашей страницы – sanjeev

ответ

0

пример с preg_replace_callback (более сильного подхода):

$str = <<<'EOD' 
[vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [/vid] 
    or 
[vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [Endvid] 
EOD; 

$format = '<div class="embed-responsive embed-responsive-16by9 vid1"><iframe class="embed-responsive-item" src="//www.youtube.com/embed/%s" allowfullscreen></iframe></div>'; 

$result = preg_replace_callback('~\Q[vid]\E \s* ([^[\s]+) \s* \Q[/vid]\E~x', 
    function ($m) use ($format) { 
     foreach (explode('&', parse_url($m[1], PHP_URL_QUERY)) as $param) { 
      list($key, $value) = sscanf($param, '%[^=]=%s'); 
      if ($key == 'v') return sprintf($format, $value); 
     }; 
     return $m[0]; 
    }, $str); 

echo $result; 

С preg_replace только (но более наивный подход):

$str = <<<'EOD' 
[vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [/vid] 
    or 
[vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [Endvid] 
EOD; 

$replacement = '<div class="embed-responsive embed-responsive-16by9 vid1"><iframe class="embed-responsive-item" src="//www.youtube.com/embed/$1" allowfullscreen></iframe></div>'; 

$result = preg_replace('~\Q[vid]\E \s* [^[\s]+ [?&] v=([^[&\s]+) \s* \Q[/vid]\E~x', $replacement, $str); 

echo $result; 
3

Logic

<?php 

$html = "he approaches very silently towards him but at the last point of time, the man gets the hint and manages to escape from the attack. , [vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [/vid] What happens in the latter is just breath-taking and comes with a reason why this video has gone viral in such short span of time"; 

function getBetweenTwoStrings ($string, $start, $end) { 
$string = " ".$string; 
$ini = strpos($string, $start); 
if ($ini == 0) return ""; 
$ini += strlen($start); 
$len = strpos($string, $end, $ini) - $ini; 
return substr($string, $ini, $len); 
} 

// Assuming you need in array as well 
$tag[0] = "[vid]"; 
$tag[1] = getBetweenTwoStrings($html, "[vid]", "[/vid]"); 
$tag[2] = "[/vid]"; 

echo $tag[0]; 
echo $tag[1]; 
echo $tag[2]; 

?> 

Выход:

[vid] youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs [/vid] 

Примечание:

Now you can play around the way you want the output. 
2

Если я тебя, я хотел бы попробовать что-то вроде этого:

preg_match_all("/(\[vid\])(.*?)(\[\/vid\])/s", $html, $tag); 

В этом случае, если у вас есть ОДНО появление тегов и содержимого, вы сможете получить к ним доступ с помощью $ tag [1] [0], $ tag [2] [0] и $ tag [3] [ 0], которые в вашем примере будет иметь значения:

$tag[1][0] = "[vid]"; 
$tag[2][0] = "youtubeURL/watch?time_continue=58&v=eED6VRcj1Rs "; 
$tag[3][0] = "[/vid]"; 

EDIT: Если вы хотите, чтобы соответствовать [VID] тегов с классами в них (например, [VID класс = "VID1"]), то нужно будет изменить регулярное выражение для этого:

preg_match_all("/(\[vid.*\])(.*?)(\[\/vid\])/s", $html, $tag); 
+0

@ г-Маргаритис выходной пришедшего: Array ( [0] => Массив ( ) [1] => Массив ( ) [2] => Массив ( ) [3] => Массив ( ) ) – sanjeev

+0

Почему с помощью модификатора м? –

+0

@CasimiretHippolyte preg_match_all ("/ (\ [vid \]) (. *) (\ [\/Vid \]) /", $ html, $ tag); вывод такой же – sanjeev

 Смежные вопросы

  • Нет связанных вопросов^_^