PHP - get certain word from string - php

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.

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]);

Remove characters from string based on user input

Suppose I have a string:
$str="1,3,6,4,0,5";
Now user inputs 3.
I want that to remove 3 from the above string such that above string should become:
$str_mod="1,6,4,0,5";
Is there any function to do the above?
You can split it up, remove the one you want then whack it back together:
$str = "1,3,6,4,0,5";
$userInput = 3;
$bits = explode(',', $str);
$result = array_diff($bits, array($userInput));
echo implode(',', $result); // 1,6,4,0,5
Bonus: Make $userInput an array at the definition to take multiple values out.
preg_replace('/\d[\D*]/','','1,2,3,4,5,6');
in place of \d just place your digit php
If you don't want to do string manipulations, you can split the string into multiple pieces, remove the ones you don't need, and join the components back:
$numberToDelete = 3;
$arr = explode(',',$string);
while(($idx = array_search($numberToDelete, $components)) !== false) {
unset($components[$idx]);
}
$string = implode(',', $components);
The above code will remove all occurrences of 3, if you want only the first one yo be removed you can replace the while by an if.

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));

Need to get middle part of path

I have a path like this
apples/oranges/bananas
I need to get the middle item in the path, in this case oranges.
What is the best way to do it? I can do it myself using strpos and substr but I imagine there is a better way...
$path = explode("/", "apples/oranges/bananas");
echo $path[1];
You could explode the string (assuming it is) and then get the correct index from the array. Like so:
$string = "apples/oranges/bananas";
$array = explode('/', $string);
echo $array[1]; //outputs oranges
Just to show off array dereferencing in PHP > 5.4:
echo explode('/', 'apple/oranges/bananas')[1];
If
$path = 'apples/oranges/bananas';
you could do:
$dir = basename(dirname($path));
if you want to start from the end of the string, and should work on Windows, or
$dir = preg_match('|/([^/]*)|', $path, $m) ? $m[1] : false;
if you want to start at the beginning of the string, and will not work on Windows.
Is it always 3 words separated by 2 slashes?
if yes, you can try:
$mypath = explode('/', 'apple/oranges/bananas');
echo $mypath[1]; //gives oranges

PHP RegEx/Substring to get ID from a string

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,

Categories