I have a string /en/products/saucony-switchback-iso/416.html and I would like to replace the first 4th character /en/ with /de/.
The result should be /de/products/saucony-switchback-iso/416.html
This is what I've tried:
$href = "/en/products/saucony-switchback-iso/416.html";
$href_replace = substr_replace($href, "/de/", 0);
its only returning "/de/"?
You also need to define the length of how much you're replacing in the string, which in your case is 4 (or 3, seeing as the trailing / is present in both) characters.
$href = "/en/products/saucony-switchback-iso/416.html";
$href_replace = substr_replace($href, "/de/", 0, 4);
echo $href_replace;
If you don't define a length as in your example, it defaults to the entire length of the string http://php.net/manual/en/function.substr-replace.php
length
If given and is positive, it represents the length of the portion of
string which is to be replaced. If it is negative, it represents the
number of characters from the end of string at which to stop
replacing. If it is not given, then it will default to strlen( string
); i.e. end the replacing at the end of string
Which is why you're only being left with /de/
If you want to replace /en/, str_replace is a better function
echo str_replace("/en/", "/de/", $href);
Technically you only need to do 3 (but whatever), it's simple.
echo "/de" .substr("/en/products/saucony-switchback-iso/416.html", 3);
Output
/de/products/saucony-switchback-iso/416.html
Sandbox
I also think substr will be about as fast as you can get it.
Related
I have multiple random strings, and I'm trying to pull "SpottedBlanket" out of the string. Some of them work fine:
DarkBaySpottedBlanket --
DarkBay
BaySpottedBlanket --
Bay
but others are cutting out more than it should.
RedRoanSpottedBlanket --
RedR
BlackSpottedBlanket --
Blac
DunSpottedBlanket --
Du
this is the code I'm using, but I thought it would be self explanatory:
$AppyShortcut = chop($AppyColor,"SpottedBlanket");
$AppyColor would obviously be the random generated string. Any clue why this is happening?
The chop function takes the string in the second argument - which in this case is "SpottedBlanket", and removes any contiguous characters that it finds from the right hand side.
So for the case of "RedRoanSpottedBlanket", you'd get back "RedR" because "o", "a", and "n" are letters that can be found in the string "SpottedBlanket".
chop() is usually used to remove trailing white space - a way of cleaning user input before performing some action on it.
Give your array:
$strings = ["DarkBaySpottedBlanket", "RedRoanSpottedBlanket", "BlackSpottedBlanket", "DunSpottedBlanket"];
What you might be looking for is somerthing like this:
foreach ($strings as $string) {
print substr($string, 0, strrpos($string, "SpottedBlanket")) . "\n";
}
This finds the position of the string from the end using strrpos(), then returns the start of the string until that position, using substr().
Using PHP I sometimes have strings that look like the following:
111
110
011
1111
0110012
What is the most efficient way (preferably without regex) to determine if a string contains any character other then the character 1?
Here's a one-line code solution that can be put into a conditional etc.:
strlen(str_replace('1','',$mystring))==0
It strips out the "1"s and sees if there's anything left.
User Don't Panic commented that str_replace could be replaced by trim:
strlen(trim($mystring, '1'))==0
which removes leading and trailing 1s and sees if there's anything left. This would work for the particular case in OP's request but the first option will also tell you how many non-"1" characters you have (if that information matters). Depending on implementation, trim might run slightly faster because PHP doesn't have to check any characters between the first and last non-"1" characters.
You could also use a string like a character array and iterate through from the beginning until you find a character which is not =='1' (in which case, return true) or reach the end of the array (in which case, return false).
Finally, though OP here said "preferably without regex," others open to regexes might use one:
preg_match("/[^1]/", $mystring)==1
Another way to do it:
if (base_convert($string, 2, 2) === $string) {
// $string has only 0 and 1 characters.
}
since your $string is basically a binary number, you can check it with base_convert.
How it works:
var_dump(base_convert('110', 2, 2)); // 110
var_dump(base_convert('11503', 2, 2)); // 110
var_dump(base_convert('9111111111111111111110009', 2, 2)); // 11111111111111111111000
If the returned value of base_convert is different from the input, there're something other characters, beside 0 and 1.
If you want checks if the string has only 1 characters:
if(array_sum(str_split($string)) === strlen($string)) {
// $string has only 1 characters.
}
You retrieve all the single numbers with str_split, and sum them with array_sum. If the result isn't the same as the length of the string, then you've other number in the string beside 1.
Another option is treat string like array of symbols and check for something that is not 1. If it is - break for loop:
for ($i = 0; $i < strlen($mystring); $i++) {
if ($mystring[$i] != '1') {
echo 'FOUND!';
break;
}
}
I have a string like any of the following:
$str = 'A001';
$str = 'B001';
$str = 'AB001';
$str = 'B0015';
....
$str = '001A';
I want to keep only 3 characters from the end of each string.
My code is like this:
$code = str_split($str);
$code = $code[1].$code[2].$code[3];
But it works for specific cases, but not for general ones! How I can get it for general ones?
I want to keep every 3 character from end of string
Simply Use substr
echo substr($str,-3); // Last 3 characters
Second parameter to this function is start, and according to the Manual
If start is negative, the returned string will start at the start'th character from the end of string.
Fiddle
Use sbstr()
echo substr($str,-3);//get last 3 char char
Or try:
echo $str[strlen($str)-3].$str[strlen($str)-2].$str[strlen($str)-1];
You need to use substr function.
All you need to do is to pass the string, and tell it where you cut the string off. If you want to cut the string off from end, you have to provide the value in negative.
substr($str, -3);
// The third argument is optional, which specifies the length of the returned string.
i'm using chunk_split to add a "-" every 4th letter, but it also add one at the end of the string, which i don't want, here's the code:
<?php
function GenerateKey($input)
{
$generated = strtoupper(md5($input).uniqid());
echo chunk_split(substr($generated, -24), 4, "-");
}
?>
Maybe not the most efficient way to generate a serial key, i think it would be better if i used mt_rand, but i think it'll do for now.
So how would i do so it doesn't add a "-" at the end of the string?
Because right now the output looks like this:
89E0-1E2E-1875-3F63-6DA1-1532-
Really appreciate the help i can get
Kind regards,
Jesper
You can remove the trialing - by rtrim. Try this
$str = "89E01E2E18753F636DA11532";
echo rtrim(chunk_split($str,4,"-"), "-");
Output:
89E0-1E2E-1875-3F63-6DA1-1532
You can chop off the - with rtrim():
echo rtrim(chunk_split(substr($generated, -24), 4, "-"), "-");
md5() generates a 32-character string.
uniqid() by default generayes a 13-character string.
You want a 24-character string with delimiting hyphens between every four characters.
You don't need to trim a trailing hyphen if you reconfigure earlier processing.
Generate the random string and prepend 3 arbitrary characters.
Call chunk_split() to apply hyphens.
Cut away the unwanted characters from the front of the string and the trailing hyphen.
Convert the isolated string to uppercase.
Return the value from your function instead of echoing.
Code: (Demo)
function GenerateKey(string $input): string
{
return strtoupper(
substr(
chunk_split(
'...' . md5($input) . uniqid(),
4,
'-'
),
-25,
24
)
);
}
echo GenerateKey('foooobar');
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.