Remove any kind of url from string in php? - php

I am having below data.
Example 1
From : http://de.example.ch/biz/barbar-vintage-z%C3%BCrich
I want: /biz/barbar-vintage-z%C3%BCrich
And also if there is
http://www.example.ch/biz/barbar-vintage-z%C3%BCrich
Then
I also want
/biz/barbar-vintage-z%C3%BCrich

If you want to do it via regex then you can use:
$s = 'http://de.example.ch/biz/barbar-vintage-z%C3%BCrich';
echo preg_replace('~^https?://[^/]+~', '', $s);
//=> /biz/barbar-vintage-z%C3%BCrich
Otherwise as the comments says parse_url function also let you have this value.

function getRelativePath($url)
{
$matches = array();
if (preg_match('#^(http://|https://)([^./]+\.)+[a-z]{2,3}(/.*)$#', $url, $matches) {
return $matches[3];
} else {
return false;
}
}

You could use preg_match or preg_match_all
preg_match('~^https?://[^/]+\K.+~', $data, $matches);
DEMO

Just try this:
<?php
$url = 'http://de.example.ch/biz/barbar-vintage-z%C3%BCrich';
echo preg_replace('~^https?://[^/]+~', '', $url);
?>

Related

Remove the first paragraph tags from string

String
"<p>This is </p><p>Stackoverflow</p><p>site for programmers</p>"
Required Output
"This is <p>Stackoverflow</p><p>site for programmers</p>"
Small function
function remove_p($string)
{
$first_p=substr($string,0,3);
$p="<p>";
if($first_p==$p)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('</p>','',$string,$temp=1);
}
return $string;
}
But it removes all the <p> </p> tags.Why so?
I am basically writing this to remove the first paragraph tags created by ckeditor.
str_replace acts on all occurrences of a substring, not just the first. You will want to use a different function.
$string = preg_replace('~<p>(.*?)</p>~is', '$1', $string, /* limit */ 1);
To only remove the first <p> and </p> if at the start of the string, add a ^ after the first /.
See also: Using str_replace so that it only acts on the first match?
function replaceFirst($input, $search, $replacement){
$pos = stripos($input, $search);
if($pos === false){
return $input;
}
else{
$result = substr_replace($input, $replacement, $pos, strlen($search));
return $result;
}
}
$string = "This is <p>Stackoverflow</p><p>site for programmers</p>";
echo $string;
echo replaceFirst($string, '<p>', '');
Output:
This is <p>Stackoverflow</p><p>site for programmers</p>
This is Stackoverflow</p><p>site for programmers</p>
Source: #2031045
Hope this helps!
$str = "This is <p>Stackoverflow</p><p>site for programmers</p>";
function remove_p($string)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('<\p>','',$string,$temp=1);
return $string;
}
echo(remove_p($str));
The result is:
This is Stackoverflow
site for programmers
Try using the method of this answer.
function remove_p($string)
{
return replaceFirst(replaceFirst($string, '<p>', ''), '</p>', '');
}
Or read about Regular Expressions.

How to find a string in a variable using PHP and regular expressions

I am trying to find the word and add a number next to it. How could he do? I tried with the code below, but I could not. Could anyone help me?
Thank you!
$string = 'I220ABCD I220ABCDEF I220ABCDEFG'
if (preg_match("/I220.*/", $string, $matches)) {
echo $matches[0];
}
Expected result:
I220ABCD9
I220ABCDEF10
I220ABCDEFG11
Use preg_replace_callback instead like this:
$str = 'I220AB FRRRR CD I221ABCDEF I220AB DSFDSF CDEFG';
$repl= preg_replace_callback('~(I220[^\s]+)~', function($m) {
static $i=9;
return $m[1] . $i++;
}, $str);
echo $repl\n"; // I220AB9 FRRRR CD I221ABCDEF I220AB10 DSFDSF CDEFG
I dont know what your requirnments for adding the number at the end are so i just incremeneted during the loop;
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
$arrayStrings = explode(" ", $string);
$int = 9;
$newString = '';
foreach($arrayStrings as $stringItem)
{
if (preg_match("/I220.*/", $stringItem, $matches))
{
$stringItem = $stringItem.$int;
$newString = $newString.$stringItem." ";
$int++;
}
}
echo $newString;
Use preg_replace_callback():
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
// This requires PHP5.3+ since it's using an anonymous function
$result = preg_replace_callback('/I220[^\s]*/', function($match){
return($match[0].rand(0,10000)); // Add a random number between 0-10000
}, $string);
echo $result; // I220ABCD3863 I220ABCDEF5640 I220ABCDEFG989
Online demo.
You'll need to use a catch block in your regex e.g. "/I220([^ ]+)/" and if you want them all, you'll need to use preg_match_all, too.
preg_replace_callback with your needs:
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
class MyClass{
private static $i = 9;
private static function callback($matches){
return $matches[0] . self::$i++;
}
public static function replaceString($string){
return preg_replace_callback('/I220[^\s]+/',"self::callback",$string);
}
}
echo(MyClass::replaceString($string));
of course you can edit to class to initialize the way you want

PHP preg match?

Okay, let's say this is a line
v1=something;v2=something2;
how to get v1 value (something) starting from = and break at ; and same to be done with v2 by calling it (v1)
function getVal($name){
// some code to start grabbing from = and end by ;
}
when i call
getVal("v1");
it should return "something"
This will work
v1=([^;]*)
The match will be in group 1
Just replace v1 in the regex with the key you want to lookup
if (preg_match('/v1=([^;]*)/', $subject, $regs)) {
$result = $regs[1];
} else {
$result = "";
}
If I understand your question, then I think this is what you are looking for:
$line = "v1=something;v2=something2;";
function getVal($name, $line){
preg_match('/'.$name.'=([^;]*)/', $line, $matches);
return $matches[1];
}
echo getVal("v1", $line);
v(?:\d*)=(\w;+)
That will match all v (with digits or no digits after it) and then the match group will be after the = sign. It is group 1.
You are obliged to sent the line to your function (or you can be dirty and use it as global).
So, your function can be something like that :
<?php
function getVal($name, $line){
// some code to start grabbing from = and end by ;
preg_match('#;?' . $name . '=([^;]+);?#', $line, $aMatches);
if(isset($aMatches[1])) {
return $aMatches[1];
}
return false;
}
$line = 'v1=something;v2=something2';
$v1 = getVal('v1',$line);
echo $v1;
?>
Use this Function:
function getVal($name, $line){
preg_match("/{$name}=(.+);(v(\d+)=|$)/U", $line, $matches);
$matches = $matches[0];
$matches = preg_replace("/{$name}=/","",$matches);
$matches = preg_replace("/;v(\d+)=/","",$matches);
return $matches;
}
this will give you exact answer.
Tested and working.:)

How do I get the Video Id from the URL? (DailyMotion)

Example:
http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun
How do I get x4xvnz?
You can use basename [docs] to get the last part of the URL and then strtok [docs] to get the ID (all characters up to the first _):
$id = strtok(basename($url), '_');
/video\/([^_]+)/
should do the trick. This grabs in the first capture all text after video/ up till the first _.
preg_match('#<object[^>]+>.+?http://www.dailymotion.com/swf/video/([A-Za-z0-9]+).+?</object>#s', $dailymotionurl, $matches);
// Dailymotion url
if(!isset($matches[1])) {
preg_match('#http://www.dailymotion.com/video/([A-Za-z0-9]+)#s', $dailymotionurl, $matches);
}
// Dailymotion iframe
if(!isset($matches[1])) {
preg_match('#http://www.dailymotion.com/embed/video/([A-Za-z0-9]+)#s', $dailymotionurl, $matches);
}
$id = $matches[1];
I use this:
function getDailyMotionId($url)
{
if (preg_match('!^.+dailymotion\.com/(video|hub)/([^_]+)[^#]*(#video=([^_&]+))?|(dai\.ly/([^_]+))!', $url, $m)) {
if (isset($m[6])) {
return $m[6];
}
if (isset($m[4])) {
return $m[4];
}
return $m[2];
}
return false;
}
It can handle various urls:
$dailymotion = [
'http://www.dailymotion.com/video/x2jvvep_coup-incroyable-pendant-un-match-de-ping-pong_tv',
'http://www.dailymotion.com/video/x2jvvep_rates-of-exchange-like-a-renegade_music',
'http://www.dailymotion.com/video/x2jvvep',
'http://www.dailymotion.com/hub/x2jvvep_Galatasaray',
'http://www.dailymotion.com/hub/x2jvvep_Galatasaray#video=x2jvvep',
'http://www.dailymotion.com/video/x2jvvep_hakan-yukur-klip_sport',
'http://dai.ly/x2jvvep',
];
Check out my github (https://github.com/lingtalfi/video-ids-and-thumbnails/blob/master/testvideo.php), I provide functions to get ids (and also thumbnails) from youtube, vimeo and dailymotion.
<?php
$output = parse_url("http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun");
// The part you want
$url= $output['path'];
$parts = explode('/',$url);
$parts = explode('_',$parts[2]);
echo $parts[0];
http://php.net/manual/en/function.parse-url.php

PHP extract text from string - trim?

I have the following XML:
<id>tag:search.twitter.com,2005:22204349686</id>
How can i write everything after the second colon to a variable?
E.g. 22204349686
if(preg_match('#<id>.*?:.*?:(.*?)</id>#',$input,$m)) {
$num = $m[1];
}
When you already have just the tags content in a variable $str, you could use explode to get everything from the second : on:
list(,,$rest) = explode(':', $str, 3);
$var = preg_replace('/^([^:]+:){2}/', '', 'tag:search.twitter.com,2005:22204349686');
I am assuming you already have the string without the <id> bits.
Otherwise, for SimpleXML:
$var = preg_replace('/^([^:]+:){2}/', '', "{$yourXml->id}");
First, parse the XML with an XML parser. Find the text content of the node in question (tag:search.twitter.com,2005:22204349686). Then, write a relevant regex, e.g.
<?php
$str = 'tag:search.twitter.com,2005:22204349686';
preg_match('#^([^:]+):([^,]+),([0-9]+):([0-9]+)#', $str, $matches);
var_dump($matches);
I suppose you have in a variable ($str) the content of id tag.
// get last occurence of colon
$pos = strrpos($str, ":");
if ($pos !== false) {
// get substring of $str from position $pos to the end of $str
$result = substr($str, $pos);
} else {
$result = null;
}
Regex seems to me inappropriate for such a simple matching.
If you dont have the ID tags around the string, you can simply do
echo trim(strrchr($xml, ':'), ':');
If they are around, you can use
$xml = '<id>tag:search.twitter.com,2005:22204349686</id>';
echo filter_var(strrchr($xml, ':'), FILTER_SANITIZE_NUMBER_INT);
// 22204349686
The strrchr part returns :22204349686</id> and the filter_var part strips everything that's not a number.
Use explode and strip_tags:
list(,,$id) = explode( ':', strip_tags( $input ), 3 );
function between($t1,$t2,$page) {
$p1=stripos($page,$t1);
if($p1!==false) {
$p2=stripos($page,$t2,$p1+strlen($t1));
} else {
return false;
}
return substr($page,$p1+strlen($t1),$p2-$p1-strlen($t1));
}
$x='<id>tag:search.twitter.com,2005:22204349686</id>';
$text=between(',','<',$x);
if($text!==false) {
//got some text..
}

Categories