php strip from text string - php

I have a string:
...<a href="http://mple.com/nCCK8.png">...
From this I am trying to strip out the
"nCCK8.png" part
I tried substr, but that requires 2 numbers and didn't work as it can be in different positions in the string. It does occur only once in the string.
The base string always has mple.com/ before the nCCK8.png part, and always "> after.
What is the easiest way to do this?

[^\/]+?\.png
$_ = null;
if (preg_match('/([^\/]+?\.png)/i',$data,$_)){
echo $_[1];
}
Working Demo: http://www.ideone.com/3IkhB

Wow, all these other answers are so complex.
$tmp = explode('/', $string);
//if you actually WANT the "nCCK8.png" part
return substr($tmp[count($tmp) - 1], 0, -2);
//if you actually want the rest of it
$tmp = $array_pop($tmp);
return substr(implode('/', $tmp), 0, -2);
Unless the string is longer than you posted, and includes other slashes, this should work.

Get the href element via simplexml or DOM (see this answer) for instance then use parse-url to get the actual file, and finaly basename:
<?php
$href = 'http://mple.com/nCCK8.png';
$url_parts = parse_url($href);
echo basename($url_parts['path']);
?>

Related

PHP Regex to get second occurance from the path

I have a path "../uploads/e2c_name_icon/" and I need to extract e2c_name_icon from the path.
What I tried is using str_replace function
$msg = str_replace("../uploads/","","../uploads/e2c_name_icon/");
This result in an output "e2c_name_icon/"
$msg=str_replace("/","","e2c_name_icon/")
There is a better way to do this. I am searching alternative method to use regex expression.
Try this. Outputs: e2c_name_icon
<?php
$path = "../uploads/e2c_name_icon/";
// Outputs: 'e2c_name_icon'
echo explode('/', $path)[2];
However, this is technically the third component of the path, the ../ being the first. If you always need to get the third index, then this should work. Otherwise, you'll need to resolve the relative path first.
Use basename function provided by PHP.
$var = "../uploads/e2c_name_icon/";
echo basename( $var ); // prints e2c_name_icon
If you are strictly want to get the last part of the url after '../uploads'
Then you could use this :
$url = '../uploads/e2c_name_icon/';
$regex = '/\.\.\/uploads\/(\w+)/';
preg_match($regex, $url, $m)
print_r ($m); // $m[1] would output your url if possible
You can trim after the str_replace.
echo $msg = trim(str_replace("../uploads/","","../uploads/e2c_name_icon/"), "/");
I don't think you need to use regex for this. Simple string functions are usually faster
You could also use strrpos to find the second last /, then trim off both /.
$path = "../uploads/e2c_name_icon/";
echo $msg = trim(substr($path, strrpos($path, "/",-2)),"/");
I added -2 in strrpos to skip the last /. That means it returns the positon of the / after uploads.
So substr will return /e2c_name_icon/ and trim will remove both /.
You'd be much better off using the native PHP path functions vs trying to parse it yourself.
For example:
$path = "../uploads/e2c_name_icon/";
$msg = basename(dirname(realpath($path))); // e2c_name_icon

Removing Known Characters From End of String

I am writing an HTML file using file_put_content(), but want to be able to add additional content later by pulling the current file contents and chopping off the known ending to the html.
So something along these lines:
$close = '</body></html>';
$htmlFile = file_get_contents('someUrl');
$tmp = $htmlFile - $close;
file_put_contents('someUrl', $tmp.'New Content'.$close);
But since I can't just subtract strings, how can I remove the known string from the end of the file contents?
substr can be used to cut off a know length from the end of a string. But maybe you should determine if your string really ends with your suffix. To reach this, you can also use substr:
if (strtolower(substr($string, -strlen($suffix))) == strtolower($suffix)) {
$string = substr($string, 0, -strlen($suffix));
}
If the case not play any role, you can omit strtolower.
On the other side you can use str_replace to inject your content:
$string = str_replace('</body>', $newContent . '</body>', $string);
Maybe, Manipulate HTML from php could be also helpful.

Trim a string until specific character appears

I want to trim a string and delete everything before a specific character, because I am using an API that gives me some unwanted data in its callback which I want to delete.
The Callback looks like this:
{"someVar":true,"anotherVar":false,"items":[ {"id":123456, [...] }
And I only want the code after the [ , so how can I split a string like this?
Thank you!
It is JSON, so you could just decode it:
$data = json_decode($string);
If you really want to trim up to a certain character then you can just find the character's position and then cut off everything before it:
if (($i = strpos($string, '[')) !== false) {
$string = substr($string, $i + 1);
}
You can use various functions. For example:
$someVar = explode('[',$string,2);
$wantedData = $someVar[1];
Or if you want only data between [ and ] then use:
$pattern = '~\[([^\]])\]~Ui';
if (preg_match($pattern,$inputString,$matches) {
$wantedData = $matches[1];
}
Edit:
Thats what you use if you want extract some string from another. But as #Dagon noticed, it's json and you can use other function to parse it. I will leave above anyway, because it's more general to the question of extracting string from another.

php - Get string before nth dash (-)

I have a string that looks something like this:
abc-def-ghi-jkl-mno-pqr-stu-vwx-yz I'd like to get the content BEFORE the 4th dash, so effectively, I'd like to get abc-def-ghi-jkl assigned to a new string, then I'd like to get mno assigned to a different string.
How could I go about doing this? I tried using explode but that changed it to an array and I didn't want to do it that way.
Try this:
$n = 4; //nth dash
$str = 'abc-def-ghi-jkl-mno-pqr-stu-vwx-yz';
$pieces = explode('-', $str);
$part1 = implode('-', array_slice($pieces, 0, $n));
$part2 = $pieces[$n];
echo $part1; //abc-def-ghi-jkl
echo $part2; //mno
See demo
http://php.net/manual/en/function.array-slice.php
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
Can you add your source code? I done this one before but I cant remember the exact source code I used. But I am pretty sure I used explode and you can't avoid using array.
EDIT: Mark M answer is right.
you could try using substr as another possible solution
http://php.net/manual/en/function.substr.php
If I see where you are trying to get with this you could also go onto substr_replace
I guess an alternative to explode would be to find the position of the 4th - in the string and then get a substring from the start of the string up to that character.
You can find the position using a loop with the method explained at find the second occurrence of a char in a string php and then use substr(string,0,pos) to get the substring.
$string = "abc-def-ghi-jkl-mno-pqr-stu-vwx-yz";
$pos = -1;
for($i=0;$i<4;$i++)
$pos = strpos($string, '-', $pos+1);
echo substr($string, 0, $pos);
Code isn't tested but the process is easy to understand. You start at the first character (0), find a - and on the next loop you start at that position +1. The loop repeats it for a set number of times and then you get the substring from the start to that last - you found.

remove part of string after substring

This may be a dupe, but I cannot seem to find a thread which matches this issue. I want to remove all chars from a string after a given sub-string - but the chars and the number of chars after the sub-string is unknown. Most solutions I have found seem to only work for removing the given sub-string itself or a fixed length after a given sub-string.
I have
$str = preg_replace('(.gif*)','.gif$',$str);
Which locates 'blahblah.gif?12345' ok, but I cannot seem to remove the chars after the sub-string '.gif'. I read that $ denotes EOS so I thought this would work, but apparently not. I also tried
'.gif$/'
and simply
'.gif'
It can be done without regex:
echo substr('blahblah.gif?12345', strpos('blahblah.gif?12345', '.gif') + 4);
// returns ?12345 this is the length of the substring ^
So the code is:
$str = 'original string';
$match = 'matching string';
$output = substr($str, strpos($str, $match) + strlen($match));
Ok, now I'm not sure if you want to keep the first or the second part of the string. Anyway, here's the code for keeping the first part:
echo substr('blahblah.gif?12345', 0, strpos('blahblah.gif?12345', '.gif') + 4);
// returns blahblah.gif ^ this is the key
And the full code:
$str = 'original string';
$match = 'matching string';
$output = substr($str, 0, strpos($str, $match) + strlen($match));
See the both examples work here: http://ideone.com/Ge30rY
Assuming (from OP's comment) that you are working with actual URLs as your source string, I believe that the best course of action here would be to use PHP's built-in functionality for working with and parsing URLs. You do this by using the parse_url() function:
(PHP 4, PHP 5)
parse_url — Parse a URL and return its components
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.
From your example: www.page.com/image.gif?123 (or even just image.gif?123) using parse_url() will look something like this:
var_dump( parse_url( "www.page.com/image.gif?123" ) );
array(2) {
["path"]=>
string(22) "www.page.com/image.gif"
["query"]=>
string(3) "123"
}
As you can see, without the need for regular expressions or string manipulations we have broken up the URL into it's separate components. No need to re-invent the wheel. Nice and clean :)
You could do this:
$str = "somecontent.gif?anddata";
$pattern = ".gif";
echo strstr($str,$pattern,true).$pattern;
// Set up string to search through
$haystack = "blahblah.gif?12345";
// Determine substring and length of it
$needle = ".gif";
$length = strlen($needle);
// Find position of last substring
$location = strrpos($haystack, $needle);
// Use location of last occurence + it's length to get new string
$newtext = substr($haystack, 0, $location+$length);

Categories