2017-09-24 107 views
0

我有這樣的刺:刪除特定字符的字符串PHP的結束

$content = "[video width="640" height="360" mp4="http://click.ir/wp-content/uploads/2017/09/Spinning_cylinder_shaped_elevator.mp4"][/video]" 

我想從'[video' to 'mp4="'刪除... 是在有任何PHPbuilt-infunction或解決方案來解決這個問題。

寬度和高度不是靜態的或在我的問題中定義

+3

[str_replace函數(http://php.net/manual/bg/function.str-replace.php)? [的preg_match](http://php.net/manual/bg/function.preg-match.php)? –

+1

可能重複[如何刪除部分字符串?](https://stackoverflow.com/questions/2192170/how-to-remove-part-of-a-string) – mega6382

+0

@ mega6382寬度和高度並不總是靜態或在我的問題中定義 –

回答

0

我假設你想獲得URL。我會使用正則表達式來獲取網址。正則表達式應該是http [\ S] *。mp4。

在這段代碼是:

$string = '[video width="640" height="360" mp4="http://click.ir/wp-content/uploads/2017/09/Spinning_cylinder_shaped_elevator.mp4"][/video]"'; 
// use regex to fetch the url 
preg_match("/http[\S]*\.mp4/", $string, $matches); 
// get first match 
$url = $matches[0]; 

// $url is http://click.ir/wp-content/uploads/2017/09/Spinning_cylinder_shaped_elevator.mp4 

有bether和URL更好的正則表達式,但在你的情況下,這會工作。根據你的傳入數據,你可以調整你的正則表達式來獲得你想要的。

見的preg_match文檔:http://php.net/manual/en/function.preg-match.php

在線正則表達式測試儀:https://www.regexpal.com/

大量的正則表達式的相關信息:http://www.regular-expressions.info/

+0

非常感謝你......問題已經解決 –

+0

好的,所以如果'url'總是以'.mp4'結尾,但如果在某些情況下不是這樣的話呢? – mega6382

+0

@ mega6382,我表示,還有其他方法可以使用正則表達式。我的正則表達式只是完成了這項工作。你提供的正則表達式要優越得多。這就是爲什麼我添加了幾個關於正則表達式的信息的鏈接,所以人們可以瞭解它。 – natheriel

0

使用正則表達式。如果我的問題得到了解決,則需要刪除字符串的url部分直到字符串的末尾。這裏是你可以使用的代碼:

<?php 
    $str = '[video width="640" height="360" mp4="http://click.ir/wp-content/uploads/2017/09/Spinning_cylinder_shaped_elevator.mp4"][/video]'; 
    $str = preg_replace_callback("/(\[video .*mp4=\")(.*)/", 'the_function', $str); 
    function the_function($matches) { 
     return $matches[1]; 
    } 
    var_dump($str); 
?> 
+0

'preg_replace_callback'?真的嗎?爲了返回數組的第一個元素? –

+0

@Codeartist在我的問題preg_replace_callback的輸入不是靜態的,寬度和高度可能會得到調整 –

+0

看到更新,現在它會考慮到數字可能會改變的帳戶。 – Codeartist

1

要提取MP4 URL部分,只需使用preg_match

preg_match('#mp4=\"(.*)\"#i', $content, $result); 
if(!empty($result[1])){ 
    $url = $result[1]; 
}else{ 
    $url = ""; 
} 
3

這是一個簡單的1行解決方案,用於刪除部分字符串,直到mp4=

$string = '[video width="640" height="360" mp4="http://click.ir/wp-content/uploads/2017/09/Spinning_cylinder_shaped_elevator.mp4"][/video]"'; 
$data = stristr($string, 'mp4="'); 
var_dump($data); 
// string(96) "mp4="http://click.ir/wp-content/uploads/2017/09/Spinning_cylinder_shaped_elevator.mp4"][/video]"" 

但如果你只是想在URL字符串:

$string = '[video width="640" height="360" mp4="http://click.ir/wp-content/uploads/2017/09/Spinning_cylinder_shaped_elevator.mp4"][/video]"'; 
preg_match('#"\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))"#', $string, $match); 
var_dump(trim($match[0],'"')); 
// string(80) "http://click.ir/wp-content/uploads/2017/09/Spinning_cylinder_shaped_elevator.mp4"