This question already has answers here:
How to remove part of a string after last comma in PHP
(3 answers)
Closed 3 years ago.
I would like to remove the last hyphen and anything after it in a string. After looking I found something that does the first hyphen but not last:
$str = 'sdfsdf-sdfsdf-abcde';
$str = array_shift(explode('-', $str));
Current String
$str = 'sdfsdf-sdfsdf-abcde';
Desired Result
$str = 'sdfsdf-sdfsdf';
You can use this preg_replace:
$repl = preg_replace('/-[^-]*$/', '', $str);
//=> sdfsdf-sdfsdf
-[^-]*$ will match - followed by 0 or more non-hyphen characters before end of line.
You can use strrpos to get the last index, and then use substr to get the desired result.
$str = 'sdfsdf-sdfsdf-abcde';
$pos = strrpos($str , "-");
if ($pos !== false) {
echo substr($str, 0, $pos);
}
You're close. Just use array_pop() instead of array_shift(). array_pop() removes last element of array. You need, of course, use implode() later to put the strign together again.
$arr = explode('-', $str);
array_pop($arr);
$str = implode('-', $arr);
It's important not to do that in one line since array_pop() works on a reference to the array and it modfies it, and then returns only removed element.
There are a few other possible solutions mentions by other answers.
This is a little bulky but it will work for you:
$str = 'sdfsdf-sdfsdf-abcde';
$pieces = explode("-",$str);
$count = count($pieces);
for ($x = 0; $x <= $count - 2; $x++) {
$desired_result .= $pieces[$x].'-';
}
$desired_result = substr($desired_result, 0, -1);
echo $desired_result;
if you have a lot of them you can use this function:
function removeLast($str){
$pieces = explode("-",$str);
$count = count($pieces);
for ($x = 0; $x <= $count - 2; $x++) {
$desired_result .= $pieces[$x].'-';
}
$desired_result = substr($desired_result, 0, -1);
return $desired_result;
}
you call it by:
$str = 'sdfsdf-sdfsdf-abcde';
$my_result = removeLast($str);
Related
I have the following string...
$string = "True is True (5-7 years)";
what I want is to get - TiT(5-7 years)
I have tried the following code but no luck...
$string = "True is True (5-7 years)";
$explodedString = explode(" ",$string);
for($i = 0; $i < 4; $i++){
$tempString = substr($explodedString[$i], 0, 1);
$finalString .= $tempString;
}
In short, I need the first three words of its initials and the remaining in bracket is as it is like this.... TiT(5-7 years). how?
This a good case for using regular expressions:
$str = 'True is True (5-7 years)';
preg_match_all('~\([^()]*\)|\b\w~', $str, $matches);
echo implode("", $matches[0]); // TiT(5-7 years)
Regex breakdown:
\([^()]*\) Match anything inside parentheses including themselves
| Or
\b\w Match first word character from a word
Your loop is going one element too far. If you want the first letter of the first 3 words, it should be $i < 3.
Then you should use array_slice() and implode() to concatenate the rest of the array.
for ($i = 0; $i < 3; $i++) {
$finalString .= $explodedString[$i][0];
}
$finalString .= implode(' ', array_slice($explodedString, 3));
DEMO
$string = "True is True (5-7 years)";
$new_string = preg_replace('/^([a-z])[a-z]+ ([a-z])[a-z]+ ([a-z])[a-z]+ (\(.+\))$/i', '$1$2$3$4', $string);
First of all.
Create an empty variable. That will be your final result
$result="";
Then youse foreach to loop your explode string.
At every part chech the first character.
If it's not ( add the first char onto the result variable.
else add the whole array element onto the result variable
foreach(explodedString as $t){
If($t[0] !="("){$result.=$t[0];} else{$result.=$t;}
}
At the end of the loop you will get what you wanted
echo $result;
I have a url. I want to parse url. I don't want to get last two value. How can I do?
$str="first-second-11.1268955-15.542383564";
As I wanted
$str="first-second";
I used this code. But I don't want to get - from last value
$arr = explode("-", $str);
for ($a = 0; $a < count($arr) - 2; $a++) {
$reqPage .= $arr[$a] . "-";
}
You can use regular expressions too.Those are patterns used to match character combinations in strings.:
W*((?i)first-second(?-i))\W*
Use the 3rd param of explode() called limit:
$str="first-second-11.1268955-15.542383564";
$arr = explode("-", $str, -2);
$reqPage = implode($arr, "-"); // contains "first-second"
Regex is the fastest way for the string manipulations. Try this.
$str="first-second-11.1268955-15.542383564";
preg_match('/^[a-z]*-{1}[a-z]*/i', $str, $matches);
$match = count($matches) > 0 ? $matches[0] : '';
echo $match;
I have a string
$str = "[xyz.hlp] into asasa jkljk [xyp.htq] zff [xrt.thg]";
I want to get the character from the string and make an array of all those characters . for example for the above string provided I shuould get and array like this
$array("xyz.hlp","xyp.htq","xrt.thg");
I tried using preg_match(); something like this but it didn't work
preg_match('/\[(.*)\]/', $str , $Fdesc);
Thanks in Advance
I got the desired output but by using loop and some php string functions
<?php
$str = "[xyz.hlp] into asasa jkljk [xyp.htq] zff [xrt.thg]";
$i = 0;
while ($i != strrpos($str, "]")) {
$f_pos = strpos($str, "[", $i); // for first position
$l_pos = strpos($str, "]", $f_pos + 1); // for the last position
$value = substr($str, $f_pos, ($l_pos - $f_pos) + 1);
echo $value;
$i = $l_pos;
}
?>
This question already has answers here:
How to strip trailing zeros in PHP
(15 answers)
Closed 7 years ago.
I have a string like this:
14522354265300000000000
I want to display it without zero values, how I can do this? I do this
$pos = strpos($route, '0');
$length = count(str_split($route));
$a = $length - $pos;
$a = substr($route, 0, $a);
but it remove 3 in the end of string. Can somebody help me?
Additional:
If string will be 123088888880, I want make it 123.
You can use rtrim for this:
echo rtrim("14522354265300000000000", "0"); // outputs: 145223542653
here's a nice algo:
<?php
$string = "14522354265300000000000";
$new_string = '';
for($i=0; $i<strlen($string) ; $i++){
if($string[$i] != '0'){
$new_string .= $string[$i];
}
}
echo $new_string;
?>
rtrim is only if you have zero's at end of string :)
You can use rtrim('14522354265300000000000', '0')
I'm trying strip every third character (in the example a period) below is my best guess and is close as ive gotten but im missing something, probably minor. Also would this method (if i could get it working) be better than a regex match, remove?
$arr = 'Ha.pp.yB.ir.th.da.y';
$strip = '';
for ($i = 1; $i < strlen($arr); $i += 2) {
$arr[$i] = $strip;
}
One way you can do it is:
<?php
$oldString = 'Ha.pp.yB.ir.th.da.y';
$newString = "";
for ($i = 0; $i < strlen($oldString ); $i++) // loop the length of the string
{
if (($i+1) % 3 != 0) // skip every third letter
{
$newString .= $oldString[$i]; // build up the new string
}
}
// $newString is HappyBirthday
echo $newString;
?>
Alternatively the explode() function might work, if the letter you're trying to remove is always the same one.
This might work:
echo preg_replace('/(..)./', '$1', 'Ha.pp.yB.ir.th.da.y');
To make it general purpose:
echo preg_replace('/(.{2})./', '$1', $str);
where 2 in this context means you are keeping two characters, then discarding the next.
A way of doing it:
$old = 'Ha.pp.yB.ir.th.da.y';
$arr = str_split($old); #break string into an array
#iterate over the array, but only do it over the characters which are a
#multiple of three (remember that arrays start with 0)
for ($i = 2; $i < count($arr); $i+=2) {
#remove current array item
array_splice($arr, $i, 1);
}
$new = implode($arr); #join it back
Or, with a regular expression:
$old = 'Ha.pp.yB.ir.th.da.y';
$new = preg_replace('/(..)\./', '$1', $old);
#selects any two characters followed by a dot character
#alternatively, if you know that the two characters are letters,
#change the regular expression to:
/(\w{2})\./
I'd just use array_map and a callback function. It'd look roughly like this:
function remove_third_char( $text ) {
return substr( $text, 0, 2 );
}
$text = 'Ha.pp.yB.ir.th.da.y';
$new_text = str_split( $text, 3 );
$new_text = array_map( "remove_third_char", $new_text );
// do whatever you want with new array