I have done a lot of search. Almost every answer is about array. In my situation, I want to remove the same number.
<?php
$term="1,2,3.4";
$n='2';
//I want to remove 2 when the $n equal one number of $term.
// echo out like 1,3,4
?>
This should work for you:
(I assume that 1,2,3.4 the dot only was a typo)
<?php
$term = "1,2,3,4";
$n = "2";
$arr = explode(",", $term);
if(($key = array_search($n, $arr)) !== FALSE)
//^^^ to make sure when '$n' is not found in the array, that it doesn't unset the first array element
unset($arr[$key]);
echo implode(",", $arr);
?>
Output:
1,3,4
I have done a lot of search.
And you didn't find str_replace() function?
$string = '1,2,3,4,5,6;'
$n = '2';
$string = str_replace($n, '', $string);
$string = str_replace(',,', ',', $string);
No need to waste memory with arrays or using regular expressions.
$term = "1,2,3,4";
$n = 2;
$term_array = explode(',', $term);
$n_key = array_search($n, $term_array);
if ($n_key !== false)
unset($term_array[$n_key]);
$new_terms = implode(',', $term_array);
Ouput :
1,3,4
Hope this helps
$n = '2';
$str = '2,1,2,3,4,5,6,2';
$pattern = '/,2|,2,|2,/';
$after = preg_replace($pattern, '', $str);
echo $after
Ouput
1,3,4,5,6
mybe it's more simple
Related
Here's my users list
james,john,mark,luke,
james,john,mark,luke,mary,david
I want to remove the repeated part and retain the remaining.
So here's my code
$old = 'james,john,mark,luke,';
$users = 'james,john,mark,luke,mary,david';
// Replace , with |
$expr = rtrim(preg_replace('/\,/', '|', $old), '|');
$newstr = preg_replace("/$expr/i", '', $users);
echo $newstr;
Output
,,,,mary,david
I want
mary,david,
A solution, based on your code using trim:
$old = 'james,john,mark,luke,';
$users = 'james,john,mark,luke,mary,david';
$expr = rtrim(preg_replace('/\,/', '|', $old), '|');
$newstr = preg_replace("/$expr/i", '', $users);
echo trim($newstr, ',');
Demo: https://3v4l.org/W3XKe
A better solution using explode, array_diff and implode:
$old = 'james,john,mark,luke,';
$users = 'james,john,mark,luke,mary,david';
$old_items = explode(',', $old);
$users_items = explode(',', $users);
echo implode(array_diff($users_items, $old_items), ',');
Demo: https://3v4l.org/tnt9F
Can't test it right now, but wouldn't it work simply like that?
$old = 'james,john,mark,luke,';
$users = 'james,john,mark,luke,mary,david';
echo preg_replace("/$old/", "", $users); //should print "mary,david"
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);
How would I extract the number 33 before the underscore in the following?
33_restoffilename.txt.
would something like following work?
int strPos = strpos("33_filename.txt", "_");
str num = substr ("33_filename.txt" , 0 , strPos );
there are may way to achive this:
Method 1:
$strPos = strpos("33_filename.txt", "_");
echo $num = substr("33_filename.txt" , 0 , $strPos );
Method 2:
$str = '33_filename.txt';
$str_arr = explode('_', $str);
echo $num = $str_arr[0];
If the naming convention is always number_filename.ext, you can use explode():
//Put the filename into the variable $name
$name = "33_restoffilename.txt";
//Split the name by "_"
$parts = explode("_", $name);
//Get the first part of the name from the array (position 1)
$number = $parts[0];
//Output
echo $number;
This will output
33
Use strstr().
$str = '33_filename.txt';
$num = strstr($str, '_', true);
Method - 1
$getIntegerFromBeginning = substr($string, 0, strspn($string, "0123456789"));
echo $getIntegerFromBeginning;
Method - 2
$getIntegerFromBeginning = explode("_", $string, 2);
echo $getIntegerFromBeginning[0];
Replace $string with exact string.
Use this
$string = '33_filename.txt';
$arrString = explode('_', $string);
echo $value = $arrString[0]; //Will output 33
This is really very simple we don't need these string functions in this case. Just do type casting and you will get integer number. It will be fast and easy
$pp='33_restoffilename.txt';
echo (int)$pp;
No need to make it complicated
How can I convert to uppercase for the following example :
title-title-title
Result should be:
Title-Title-Title
I tried with ucwords but it converts like this: Title-title-title
I currently have this:
echo $title = ($this->session->userdata('head_title') != '' ? $this->session->userdata('head_title'):'Our Home Page');
In this particular string example, you could explode the strings first, use that function ucfirst() and apply to all exploded strings, then put them back together again:
$string = 'title-title-title';
$strings = implode('-', array_map('ucfirst', explode('-', $string)));
echo $strings;
Should be fairly straightforward on applying this:
$title = '';
if($this->session->userdata('head_title') != '') {
$raw_title = $this->session->userdata('head_title'); // title-title-title
$title = implode('-', array_map('ucfirst', explode('-', $raw_title)));
} else {
$title = 'Our Home Page';
}
echo $title;
echo str_replace(" ","-",ucwords(str_replace("-"," ","title-title-title")));
Fiddle
Output:
Title-Title-Title
Demo
Not as swift as Ghost's but a touch more readable for beginners to see what's happening.
//break words on delimiter
$arr = explode("-", $string);
//capitalize first word only
$ord = array_map('ucfirst', $arr);
//rebuild the string
echo implode("-", $ord);
The array_map() applies callback to the elements of the given array. Internally, it traverses through the elements in our word-filled array $arr and applies the function ucfirst() to each of them. Saves you couple of lines.
Edit #2
This isn't working for the new information added to op, as there is an answer this won't be updated to reflect that.
Edit #1
$var = "title-title-title";
$var = str_replace (" ", "_", ucwords (str_replace (" ", "_", $var));
Old, non-working
$var = "title-title-title";
$var = implode("-", ucwords (explode("-", $var)));
try the following:
$str='title-title-title';
$s='';
foreach(explode('-',$str) as $si){
$s.= ($s ? "-":"").ucfirst($si);
}
$s should be Title-Title-Title at this point
*strong text*i have a string like that "x", "x,y" , "x,y,h"
i want to user preg replace to remove the commas inside the double qutations and return the string as
"x", "xy" , "xyh"
You can just use a regular replace.
$mystring = str_replace(",", "", $mystring);
You dont need preg_replace() here and whereever possible you should trying to avoid it
$string = str_replace(',', '', $string);
This would work fine: http://codepad.org/lq7I5wkd
<?php
$myStr = '"x", "x,y" , "x,y,h"';
$chunks = preg_split("/\"[\s]*[,][\s]*\"/", $myStr);
for($i=0;$i<count($chunks);$i++)
$chunks[$i] = str_replace(",","",$chunks[$i]);
echo implode('","',$chunks);
?>
I use the following, which I've found is generally faster than regexp for this type of replacement
$string = '"x", "x,y" , "x,y,h"';
$temp = explode('"',$string);
$i = true;
foreach($temp as &$value) {
// Only replace in alternating array entries, because these are the entries inside the quotes
if ($i = !$i) {
$value = str_replace(',', '', $value);
}
}
unset($value);
// Then rebuild the original string
$string = implode('"',$temp);