PHP RegEx/Substring to get ID from a string - php

Here is my string:
**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**
I want to take the last section /NHg5XdqFb5b/ and remove the slashes.
Also are there any tools available to attemtp to work this out?

You can do this by:
<?php
$id = explode("/", "**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**");
$myID = $id[count($id)-2];
?>
Or if you want to use regex: (make sure all ids are 11 in length)
preg_match("/[a-zA-Z0-9]{11}/i", "**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**", $matches);
echo($matches[0]);

You could do a preg_replace http://ch.php.net/preg_replace
$var = preg_replace('~.*/([^/]+)/\*\*~','$1',$var);

You can use explode, which will split the string and return an array
$arr = explode("/", your_string_here); //split string by "/"
$id = $arr[count($arr) - 2]; //in your case, get the second-last part
Alternatively,
$arr = preg_match("\/posts\/(.*?)\/", your_string_here); //matches /posts/NHg5XdqFb5b/
//$arr[0] = whole match
//$arr[1] = 1st capture group (part between brackets) in your regex, i.e. required id
$id = $arr[1];
Cheers,

Related

How can I get the end of a string in PHP?

Substr PHP
I have a string like http://domain.sf/app_local.php/foo/bar/33.
The last characters are the id of an element. Its length could be more than one, so I can not use:
substr($dynamicstring, -1);
In this case, it must be:
substr($dynamicstring, -2);
How can I get the characters after "/bar/" on the string without depending on the length?
To ensure you are getting an immediate section after the bar, use regular expressions:
preg_match('~/bar/([^/?&#]+)~', $url, $matches);
echo $matches[1]; // 33
You can use explode(), like this:
$id = explode('/',$var);
And take the element where you had the id.
You could use explode('/', $dynamicstring) to split the string into an array of the strings inbetween each /. Then you could use end() on the result of this to get the last part.
$id = end(explode('/', $dynamicstring));
Try this:
$dynamicstring = 'http://domain.sf/app_local.php/foo/bar/33';
// split your string into an array with /
$parts = explode('/', $dynamicstring);
// move the array pointer to the end
end($parts);
// return the current position/value of the $parts array
$id = current($parts);
// reset the array pointer to the beginning => 0
// if you want to do any further handling
reset($parts);
echo $id;
// $id => 33
Test it yourself here.
You can use a regular expression to do it:
$dynamicstring = "http://domain.sf/app_local.php/foo/bar/33";
if (preg_match('#/([0-9]+)$#', $dynamicstring, $m)) {
echo $m[1];
}
I tested it out myself before answering. Other answers are reasonable too, but this will work according to your need...
<?php
$url = "http://domain.sf/app_local.php/foo/bar/33";
$id = substr($url, strpos($url, "/bar/") + 5);
echo $id;
Please find the below answer.
$str = "http://domain.sf/app_local.php/foo/bar/33";
$splitArr = explode('/', explode('//', $str)[1]);
var_dump($splitArr[count($splitArr)-1]);

Removing last part of string divided by a colon

I have a string that looks a little like this, world:region:bash
It divides folder names, so i can create a path for FTP functions.
However, i need at some points to be able to remove the last part of the string, so, for example
I have this world:region:bash
I need to get this world:region
The script wont be able to know what the folder names are, so some how it needs to be able to remove the string after the last colon.
$res=substr($input,0,strrpos($input,':'));
I should probably highlight that strrpos not strpos finds last occurrence of a substring in given string
$tokens = explode(':', $string); // split string on :
array_pop($tokens); // get rid of last element
$newString = implode(':', $tokens); // wrap back
You may want to try something like this:
<?php
$variable = "world:region:bash";
$colpos = strrpos($variable, ":");
$result = substr($variable, 0, $colpos);
echo $result;
?>
Or... if you create a function using this information, you get this:
<?php
function StrRemoveLastPart($string, $delimiter)
{
$lastdelpos = strrpos($string, $delimiter);
$result = substr($string, 0, $lastdelpos);
return $result;
}
$variable = "world:region:bash";
$result = StrRemoveLastPart($variable, ":");
?>
Explode the string, and remove the last element.
If you need the string again, use implode.
$items = array_pop(explode(':', $the_path));
$shotpath = implode(':', $items);
Use regular expression /:[^:]+$/, preg_replace
$s = "world:region:bash";
$p = "/:[^:]+$/";
$r = '';
echo preg_replace($p, $r, $s);
demo
Notice how $ which means string termination, is made use of.
<?php
$string = 'world:region:bash';
$string = implode(':', explode(':', $string, -1));

Increment integer at end of string

I have a string, "Chicago-Illinos1" and I want to add one to the end of it, so it would be "Chicago-Illinos2".
Note: it could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't do substr.
Any suggested solutions?
Complex solutions for a really simple problem...
$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2
If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').
If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')
Try this
preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);
(can't try it now but it should work)
$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;
$string .= $number;
Tested, works.
explode could do the job aswell
<?php
$str="Chicago-Illinos1"; //our original string
$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>
I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).
You can use preg_match to accomplish this:
$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;
The following will output:
Chicago-Illinos11
However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.
$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);
If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)
$str = 'Chicago-Illinos1';
echo ++$str;
http://php.net/manual/en/language.operators.increment.php

PHP - strip URL to get tag name

I need to strip a URL using PHP to add a class to a link if it matches.
The URL would look like this:
http://domain.com/tag/tagname/
How can I strip the URL so I'm only left with "tagname"?
So basically it takes out the final "/" and the start "http://domain.com/tag/"
For your URL
http://domain.com/tag/tagname/
The PHP function to get "tagname" is called basename():
echo basename('http://domain.com/tag/tagname/'); # tagname
combine some substring and some position finding after you take the last character off the string. use substr and pass in the index of the last '/' in your URL, assuming you remove the trailing '/' first.
As an alternative to the substring based answers, you could also use a regular expression, using preg_split to split the string:
<?php
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);
?>
(The reason for the -2 is because due to the ending /, the final element of the array will be a blank entry.)
And as an alternate to that, you could also use preg_match_all:
<?php
$ptn = "/[a-z]+/";
$str = "http://domain.com/tag/tagname/";
preg_match_all($ptn, $str, $matches);
$tagname = $matches[count($matches)-1];
echo($tagname);
?>
Many thanks to all, this code works for me:
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);

PHP - get certain word from string

If i have a string like this:
$myString = "input/name/something";
How can i get the name to be echoed? Every string looks like that except that name and something could be different.
so the only thing you know is that :
it starts after input
it separated with forward slashes.
>
$strArray = explode('/',$myString);
$name = $strArray[1];
$something = $strArray[2];
Try this:
$parts = explode('/', $myString);
echo $parts[1];
This will split your string at the slashes and return an array of the parts.
Part 1 is the name.
If you only need "name"
list(, $name, ) = explode('/', $myString);
echo "name is '$name'";
If you want all, then
list($input, $name, $something) = explode('/', $myString);
use the function explode('/') to get an array of array('input', 'name', 'something'). I'm not sure if you mean you have to detect which element is the one you want, but if it's just the second of three, then use that.

Categories