I need to search for
src="http://www.domain.com/wp-content/uploads/2010/12/6a00e54fa8abf788330147e0622c2e970b-800wi.jpg"
and get
"http://www.domain.com/wp-content/uploads/2010/12/"
Since I never know how long the string is I need to get everything up to the last /
have a look at pathinfo()
ETA due to question edit:
#Chris: what you're trying to do is parse the DOM and pull out the values of src attributes. The easiest and most foolproof way to do this is to use a DOM parser. Have a look at DomDocument::loadHTML and the rest of the DOMDocument class.
Use stripos()
$val = substr($url, 0, stripos($url, '/'));
how about this:
$str = 'src="http://www.domain.com/wp-content/uploads/2010/12/6a00e54fa8abf788330147e0622c2e970b-800wi.jpg"';
$str = substr($str,5);
$str = substr($str,0,-1);
echo dirname($str)."/";
You can loop the string in reverse and look for the 1st '\' that you encounter, mark it's position, then copy the string up to that point into another string.
$resulted_path = "";
for($i = strlen($str)-1 ; ($i>=0) && ($str{$i} != '/') ; $i --);
strncpy($resulted_path, $str, $i);
Do not forget the ';' after the for loop.
The resulting string should contain your desired string.
References:
charAt |
strncpy |
strlen
Related
i have a path like this:
/dude/stuff/lol/bruh.jpg
i want to echo it like this:
/stuff/lol/bruh.jpg
how to do this? and if you could please explain it. i found one good answer
Removing part of path in php but i cannot work my way around with explode and implode.
please give me the link to the duplicate answer if my question is a duplicate
You could use strpos with substr:
$string = '/dude/stuff/lol/bruh.jpg';
$string = substr($string, strpos($string, '/', 1));
The strpos to look for the position of the / after the first one, then use substr to get the string starting from that position till the end.
$path = '/dude/stuff/lol/bruh.jpg';
$path = explode('/', $path);
unset($path[1]);
$path = implode('/', $path);
Will separate the string into an array, then unset the first item (technically the second in the array, since the first element will be empty due to the string starting with /). Finally the path is imploded, and you get:
/stuff/lol/bruh.jpg
Try this :
$string = "/dude/stuff/lol/bruh.jpg";
$firstslash = strpos($string,"/",1);
$secondstring = substr($string, $firstslash+1);
echo "String : " . $string;
echo " <br> Result : " . $secondstring;
You can use a regular expression to extract resource name you need.
preg_match('/(?P<name>[^\/]+)$/', $path, $match);
Then you have to use $match as array, and you can see the name inside of it.
$match['name];
I need help finding something in a variable that isn't always the same, and then put it in another variable.
I know that what I'm looking for has 5 slashes, it starts with steam://joingame/730/ and after the last slash there are 17 numbers.
Edit: It doesn't end with a slash, thats why I need to count 17 numbers after the fifth slash
Assuming what you're looking for looks something like this:
steam://joingame/730/11111111111111/
Then you could use explode() as a simple solution:
$gameId = explode('/', 'steam://joingame/730/11111111111111/');
var_dump($gameId[4]);
or you could use a regex as a more complex solution:
preg_match('|joingame/730/([0-9]+)|', 'steam://joingame/730/11111111111111/', $match);
var_dump($match[1]);
This splits the string into an array then return the last element as the game_id. It doesn't matter how many slashes. It will always return the last one.
$str = 'steam://joingame/730';
$arr = explode("/", $str) ;
$game_id = end($arr);
Following on from what DragonSpirit said
I modified there code so the string can look like
steam://joingame/730/11111111111111
or
steam://joingame/730/11111111111111/
$str = 'steam://joingame/730/11111111111111/';
$rstr = strrev( $str ); // reverses the string so it is now like /1111111111...
if($rstr[0] == "/") // checks if now first (was last ) character is a /
{
$nstr = substr($str, 0, -1); // if so it removes the /
}
else
{
$nstr = $str; // else it dont
}
$arr = explode("/", $nstr) ;
$game_id = end($arr);
Thanks for the help, I've found a solution for the problem. I'm going to post an uncommented version of the code on pastebin, becuase I couldn't get the code saple thing working here.
code
i have this URI.
http://localhost/index.php?properties&status=av&page=1
i am fetching basename of the URI using following code.
$basename = basename($_SERVER['REQUEST_URI']);
the above code gives me following string.
index.php?properties&status=av&page=1
i would want to remove the last variable from the string i.e &page=1. please note the value for page will not always be 1. keeping this in mind i would want to trim the variable this way.
Trim from the last position of the string till the first delimiter i.e &
Update :
I would like to remove &page=1 from the string, no matter in which position it is on.
how do i do this?
Instead of hacking around with regular expression you should parse the string as an url (what it is)
$string = 'index.php?properties&status=av&page=1';
$parts = parse_url($string);
$queryParams = array();
parse_str($parts['query'], $queryParams);
Now just remove the parameter
unset($queryParams['page']);
and rebuild the url
$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
There are many roads that lead to Rome. I'd do it with a RegEx:
$myString = 'index.php?properties&status=av&page=1';
$myNewString = preg_replace("/\&[a-z0-9]+=[0-9]+$/i","",$myString);
if you only want the &page=1-type parameters, the last line would be
$myNewString = preg_replace("/\&page=[0-9]+/i","",$myString);
if you also want to get rid of the possibility that page is the only or first parameter:
$myNewString = preg_replace("/[\&]*page=[0-9]+/i","",$myString);
Thank you guys but i think i have found the better solution, #KingCrunch had suggested a solution i extended and converted it into function. the below function can possibly remove or unset any URI variable without any regex hacks being used. i am posting it as it might help someone.
function unset_uri_var($variable, $uri) {
$parseUri = parse_url($uri);
$arrayUri = array();
parse_str($parseUri['query'], $arrayUri);
unset($arrayUri[$variable]);
$newUri = http_build_query($arrayUri);
$newUri = $parseUri['path'].'?'.$newUri;
return $newUri;
}
now consider the following uri
index.php?properties&status=av&page=1
//To remove properties variable
$url = unset_uri_var('properties', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?page=1&status=av
//To remove page variable
$url = unset_uri_var('page', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?properties=&status=av
hope this helps someone. and thank you #KingKrunch for your solution :)
$pos = strrpos($_SERVER['REQUEST_URI'], '&');
$url = substr($_SERVER['REQUEST_URI'], 0, $pos - 1);
Documentation for strrpos.
Regex that works on every possible situation: /(&|(?<=\?))page=.*?(?=&|$)/. Here's example code:
$regex = '/(&|(?<=\?))page=.*?(?=&|$)/';
$urls = array(
'index.php?properties&status=av&page=1',
'index.php?properties&page=1&status=av',
'index.php?page=1',
);
foreach($urls as $url) {
echo preg_replace($regex, '', $url), "\n";
}
Output:
index.php?properties&status=av
index.php?properties&status=av
index.php?
Regex explanation:
(&|(?<=\?)) -- either match a & or a ?, but if it's a ?, don't put it in the match and just ignore it (you don't want urls like index.php&status=av)
page=.*? -- matches page=[...]
(?=&|$) -- look for a & or the end of the string ($), but don't include them for the replacement (this group helps the previous one find out exactly where to stop matching)
You could use a RegEx (as Chris suggests) but it's not the most efficient solution (lots of overhead using that engine... it's easy to do with some string parsing:
<?php
//$url="http://localhost/index.php?properties&status=av&page=1";
$base=basename($_SERVER['REQUEST_URI']);
echo "Basename yields: $base<br />";
//Find the last ampersand
$lastAmp=strrpos($base,"&");
//Filter, catch no ampersands found
$removeLast=($lastAmp===false?$base:substr($base,0,$lastAmp));
echo "Without Last Parameter: $removeLast<br />";
?>
The trick is, can you guarantee that $page will be stuck on the end? If it is - great, if it isn't... what you asked for may not always solve the problem.
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
$link = http://site.com/view/page.php?id=50&reviews=show
How can we add &extra=video after id=50?
id is always numeric.
url can have many other variables after ?id=50
&extra=video should be added before the first & and after the 50 (value of id)
It will be used this way:
echo 'Get video';
Thanks.
As Treffynnon says, the order seldomly matters. However, if you really need if for some reason, just use
parse_url to get the querystring
parse_str to create an array of parameter
array_splice to inject a parameter
http_build_query to rebuild a proper query string
This will do it for you
<?php
$linkArray = explode('&',$link);
$linkArray[0] += '&extra=video';
$link = implode('&',$linkArray);
?>
Explode will split the link string at every &, so it doesn't care how many elements you have in the url.
The first element, will be everything including the id=## before the first & sign. So we append whatever you want to appear after it.
We put our array together again as a string, separating each element by an &.
Is ID always the first post parameter? If so, then you could jsut do some sort of string manipulation. Use strpos($link, "&") to find out the position where you want to insert. Then do a few substr() based on that position and then append them all together. Its kind of hacky I know, but it will definitely work.
$pos = strpos($link, "&");
$first = substr($link, 0, $pos);
$last = substr($link, $pos);
$extra = "&extra=video";
$newLink = $first . $extra . $last;
See this link for some of the string manipulation functions that I mentioned above: http://us3.php.net/strings
i would suggest to use functions specifically aimed at url parsing, not general string functions:
$link = 'http://site.com/view/?id=50&reviews=show';
$query = array();
parse_str(parse_url($link, PHP_URL_QUERY), $query);
$query['extra'] = 'video';
$linkNew = http_build_url($link, array('query' => http_build_query($query)));