I need cut from page url www. using php trim() function.
But this function cut and first letter, why?
$domain = parse_url('http://wordpresas.com/page/1');
$domain['host'] = trim($domain['host'], 'www.');
pr($domain['host']); //ordpresas.com
As other have stated the second parameter of trim() contains a list of characters which get trimmed.
However you can use preg_replace() for this. This will make sure only www. will be stripped if the string starts with it.
preg_replace('/^www./', '', $domain['host']);
The most effective way to do this is probably:
if( strncmp( 'www.', $domain['host'], 4) == 0){
$domain['host'] = substr( $domain['host'], 4);
}
It should have complexity O(1) :)
Related
I have a text.
$text='userpics/115/X3WGOC0009JA.jpg';
I want to add a letter p before X3WGOC0009JA.jpg, so my output will be
$text='userpics/115/pX3WGOC0009JA.jpg';
---^
I am new to php, so I don't really know what to try, I was hoping you could guide me in the right direction
You can explode by the slash by one way.
$exploded_text = explode('/', $text);
$new_text = $exploded_text[0] . $exploded_text[1] . 'p' . $exploded_text[2];
It's not the best way, but it will work.
Based on his question, I think all he wants to do is:
$text='userpics/115/'.'p'.'X3WGOC0009JA.jpg';
First, I would get the filename using strrpos and substr:
$text = 'userpics/115/X3WGOC0009JA.jpg';
$prepend_filename = 'p';
$last_slash_pos = strrpos($text, '/');
if ($last_slash_pos === false) throw new Exception('No slashes found');
$path = substr($text, 0, $last_slash_pos);
$filename = substr($text, $last_slash_pos + 1); // Add one to skip slash
And then you can add the p (as specified in $prepend_filename) using this:
$new_path = $path . DIRECTORY_SEPARATOR . $prepend_filename . $filename;
Have you tried just setting you variables and concatenation if you doing this a bunch.
$p = 'p';
$new = "userpics/115/" . $p . "X3WGOC0009JA.jpg";
There is a function, substr_replace(), which can insert a string at a point you want.
We combine this with strRpos() which we can use to find the first slash, LOOKING IN REVERSE:
$string = substr_replace($string, 'p', strrpos($string, '/')+1 );
This will insert 'p' in $string. At the position of the '/' in $string. The +1 corrects the 'cursor' to the character AFTER the slash.
Why not use the explode functions?
Very simple: Those are slow. String functions like strpos() and substr_replace() are VERY fast, especially on small strings.
Arrays are WAY slower in php, so don't go there unless you have to. For simple string- manipulation you should use simple string functions (sounds easy when you put it like that doesnt it?).
In a simple test I benchmarked the explode variant like user3758531's VS the string variant like mine:
100.000 tries with arrays: 1.5 sec
100.000 tries with strings: 0.9 sec
In this one situation, with this one action timing doesnt really matter. But apply this way of thinking thoughout the website and you will notice it speeding up/slowing down.
I know it may sound as a common question but I have difficulty understanding this process.
So I have this string:
http://domain.com/campaign/tgadv?redirect
And I need to get only the word "tgadv". But I don't know that the word is "tgadv", it could be whatever.
Also the url itself may change and become:
http://domain.com/campaign/tgadv
or
http://domain.com/campaign/tgadv/
So what I need is to create a function that will get whatever word is after campaign and before any other particular character. That's the logic..
The only certain thing is that the word will come after the word campaign/ and that any other character that will be after the word we are searching is a special one ( i.e. / or ? )
I tried understanding preg_match but really cannot get any good result from it..
Any help would be highly appreciated!
I would not use a regex for that. I would use parse_url and basename:
$bits = parse_url('http://domain.com/campaign/tgadv?redirect');
$filename = basename($bits['path']);
echo $filename;
However, if want a regex solution, use something like this:
$pattern = '~(.*)/(.*)(\?.*)~';
preg_match($pattern, 'http://domain.com/campaign/tgadv?redirect', $matches);
$filename = $matches[2];
echo $filename;
Actually, preg_match sounds like the perfect solution to this problem. I assume you are having problems with the regex?
Try something like this:
<?php
$url = "http://domain.com/campaign/tgadv/";
$pattern = "#campaign/([^/\?]+)#";
preg_match($pattern, $url, $matches);
// $matches[1] will contain tgadv.
$path = "http://domain.com/campaign/tgadv?redirect";
$url_parts = parse_url($path);
$tgadv = strrchr($url_parts['path'], '/');
You don't really need a regex to accomplish this. You can do it using stripos() and substr().
For example:
$str = '....Your string...';
$offset = stripos($str, 'campaign/');
if ( $offset === false ){
//error, end of h4 tag wasn't found
}
$offset += strlen('campaign/');
$newStr = substr($str, $offset);
At this point $newStr will have all the text after 'campaign/'.
You then just need to use a similar process to find the special character position and use substr() to strip the string you want out.
You can also just use the good old string functions in this case, no need to involve regexps.
First find the string /campaign/, then take the substring with everything after it (tgadv/asd/whatever/?redirect), then find the next / or ? after the start of the string, and everything in between will be what you need (tgadv).
Is there a simple way to use ltrim() to remove a single instance of a match instead of all matches?
I'm looping through array of strings and I'd like to remove the first, and only first, match (vowels in this case):
ltrim($value, "aeiouyAEIOUY");
With default behavior the string aardvark or Aardvark would be trimmed to be "rdvark". I'd like result to be "ardvark".
I'm not bound to ltrim by any means but it seemed the closest built-in PHP function. It would be nice of ltrim and rtrim had an optional parameter "limit", just saying... :)
Just use preg replace it has a limit option
eg
$value = preg_replace('/^[aeiouy]/i', '', $value, 1);
Regular expressions is probably overkill, but:
$value = preg_replace('/^[aeiouy]/i', '', $value);
Note the i makes it case-insensitive.
You can't use ltrim to do this for the reasons you say, nor can you use str_replace (which also has no limit). I think it's easiest just to use a regex:
$value = preg_replace('/^[aeiouy]/i', '', $value);
However if you really don't want to do that, you can use a substring, but you would have to check the position of any of those strings in the string in a loop as there is no php function that does such a check that I know of.
You can use the preg_replace function:
<?php
$value = preg_replace('/^[aeiouy]/i', '', $value);
?>
There are several way you can go about doing what you are looking to do.
Perhaps most straightforward would be a regular expression replacement like this:
$pattern = '/^[aeiouy]{1}/i';
$result = preg_replace($pattern, '', $original_string);
This is probably the most efficient way (so ignore my regular expressions answer):
if (strpos('aeiouyAEIOUY', $value[0]) !== false) $value = substr($value, 1);
Or,
if (stripos('aeiouy', $value[0]) !== false) $value = substr($value, 1);
assuming i have these texts 'x34' , '150px' , '650dpi' , 'e3r4t5' ... how can i get only numbers ? i mean i want 34 , 150 , 650 , 345 without any other character . i mean get the numbers this string has into one variable .
$str = "e3r4t5";
$str_numbers_only = preg_replace("/[^\d]/", "", $str);
// $number = (int) $str;
Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.
filter_var
flags for the filters
e.g. to get just numbers from the given string
<?php
$a = '!a-b.c3#j+dk9.0$3e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>
To adhere to more strict standards for your question, I have updated my answer to give a better result.
I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.
Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.
Edit:
1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT
2: If you have a PHP version less than 5.4, then kindly use array('+', '-') instead of the short array syntax ['+', '-'].
You can use a regular expression to remove any character that is not a digit:
preg_replace('/\D/', '', $str)
Here the pattern \D describes any character that is not a digit (complement to \d).
Use PHP FILTER functions if you are using PHP 5.2.X, 5.3.x,5.4 . Its highly recommended
$mixed_input = "e3r4t5";
$only_numbers = filter_var($mixed_input, FILTER_SANITIZE_NUMBER_INT);
Please Go through with this link to know more
Replace everything that isn't a number and use that value.
$str = "foo1bar2baz3";
$num = intval(preg_replace("/[^0-9]/", "", $str));
You could use the following function:
function extract_numbers($string) {
preg_match_all('/([\d]+)/', $string, $match);
return $match;
}
I'm trying to trim some youtube URLs that I am reading in from a playlist. The first 3 work fine and all their URLs either end in caps or numbers but this one that ends in a lower case g is getting trimmed one character shorter than the rest.
for ($z=0; $z <= 3; $z++)
{
$ythref2 = rtrim($tubeArray["feed"]["entry"][$z]["link"][0]["href"], '&feature=youtube_gdata');
The URL is http://www.youtube.com/watch?v=CuE88oVCVjg&feature=youtube_gdata .. and it should get trimmed down to .. http://www.youtube.com/watch?v=CuE88oVCVjg but instead it is coming out as http://www.youtube.com/watch?v=CuE88oVCVj.
I think it may be the ampersand symbol but I am not sure.
The second argument to rtrim is a list of characters to remove, not a string to remove.
You might want to use str_replace, or use parse_url and parse_str to get arrays of the components of the URL and the components of the query string, like "v".
Untested example code:
$youtube_url = 'http://www.youtube.com/watch?v=CuE88oVCVjg&feature=youtube_gdata';
$url_bits = parse_url($youtube_url);
$query_string = array();
parse_str($url_bits['query'], $query_string);
$video_identifier = $query_string['v']; // "CuE88oVCVjg"
$rebuilt_url = 'http://www.youtube.com/watch?v=' . $video_identifier;
No, it's the g in the second argument. rtrim() does not remove a string from the end, it removes any characters given in the second argument. Use preg_replace() or substr() instead.