I have a string with underscores(_). What I want is to get the string value after the first underscore and considered as the first string value and the second string value will be the whole string after the underscore of the first string value using php.
Example:
$string = "Makes_me_wonder";
Result I want:
$str1 = "me";
$str2 = "wonder";
Another variable I am having:
$string = "I_wont_gohome_withoutyou";
Result should be:
$str1 = "wont";
$str2 = "gohome_withoutyou";
Another one:
$string = 'Never_gonna_leave_this_bed";
Output i want:-
$str1 = "gonna_leave";
$str2 = "this_bed";
Please help me. Thanks.
You can use explode with 3rd parameter - limit:
DEMO
$string = "I_wont_gohome_withoutyou";
$arr = explode("_",$string,3);
$str1 = $arr[1]; //wont
$str2 = $arr[2]; //gohome_withoutyou
Provided that you have two or more _ in a word strictly. If it is so, there needs a work around too.
function explode($string)
{
$delimiter = '_';
return explode($delimiter, explode($delimiter, $string, 2)[1], 2);
}
$string = "Makes_me_wonder";
$strings = explode($string);
echo $strings[0]; //me
echo $strings[1]; //wonder
$string = "I_wont_gohome_withoutyou";
$strings = explode($string);
echo $strings[0]; //wont
echo $strings[1]; //gohome_withoutyou
I think your solution is like this:-
<?php
function getfinal_result($string){
$final_data = explode('_',$string,2)[1]; // explode with first occurrence of _ and leave first word
if(substr_count($final_data,'_')>2){ // now check _ remains is greater that 2
$first_data = substr($final_data , 0, strpos($final_data , '_', strpos($final_data , '_')+1)); // find the string comes after second _
$second_data = str_replace($first_data.'_','',$final_data); // get the string before the second _
$last_data = Array($first_data,$second_data); // assign them to final data
}else{
$last_data = explode('_',$final_data,2); // directly explode with first occurance of _
}
return $last_data; // return final data
}
$first_data = getfinal_result('Makes_me_wonder');
$second_data = getfinal_result('I_wont_gohome_withoutyou');
$third_data = getfinal_result('Never_gonna_leave_this_bed');
echo "<pre/>";print_r($first_data);
echo "<pre/>";print_r($second_data);
echo "<pre/>";print_r($third_data);
?>
Output:- https://eval.in/593240
There are multiple methods but here's one of them.
$pos1 = strpos($string, '_');
$pos2 = strpos($string, '_', $pos1 + 1);
$str1 = substr($string, $pos1 + 1, $pos2 - $pos1 - 1);
$str2 = substr($string, $pos2 + 1);
This assumes that there are at least 2 underscores in the string.
Related
For example
$string = "Hello world.";
"lo" will get replaced with "aa" and "ld" will get replaced with "bb".
Output will be
$string = "Helaa worbb";
This should work -
$string = "Hello world.";
// pairs to replace
$replace_pairs = array("lo" => 'aa', 'ld' => 'bb');
// loop through pairs
foreach($replace_pairs as $replace => $new)
{
// if present
if(strpos($string, $replace)) {
// explode the string with the key to replace and implode with new key
$string = implode($new, explode($replace, $string));
}
}
echo $string;
Demo
This is what I came up, you can optimize this code.
// assuming only 2 characters find and replace
$string = "Hello world.";
$aa = str_split($string); //converts string into array
$rp1 = 'aa'; //replace string 1
$rp2 = 'bb'; //replace string 2
$f1 = 'lo'; //find string 1
$f2 = 'ld'; // find string 2
function replaceChar($k1, $k2, $findStr, $replaceStr, $arr){
$str = $arr[$k1].$arr[$k2];
if($str == $findStr){
$ra = str_split($replaceStr);
$arr[$k1] = $ra[0];
$arr[$k2] = $ra[1];
}
return $arr;
}
for($i=0; $i < count($aa)-1; $i++){
$k1 = $i;
$k2 = $i+1;
$aa = replaceChar($k1, $k2, $f1, $rp1, $aa); //for replace first match string
$aa = replaceChar($k1, $k2, $f2, $rp2, $aa); // for replace second match string
}
echo implode('', $aa);
Demo
I have this code
<?php
$str1 = 'Good'
$str2 = 'Weather'
echo $str1, $str2
I need the output as Doog Reathew
Using the below piece of code solves your purpose. Comments have been added for your understanding.
<?php
$str1 = 'Good';
$str2 = 'Weather';
function swaprev($str1)
{
$str1 = str_split($str1); //<--- Split the string into separate chars
$lc=$str1[count($str1)-1]; # Grabbing last element
$fe=$str1[0]; # Grabbing first element
$str1[0]=$lc;$str1[count($str1)-1]=$fe; # Do the interchanging
return $str1 = implode('',$str1); # Recreate the string
}
echo ucfirst((strtolower(swaprev($str1))))." ".ucfirst((strtolower(swaprev($str2))));
OUTPUT :
Doog Reathew
just write below function ,it will work
function replace($string) {
$a = substr($string, 0, 1);
$b = substr($string, -1);
$string = $b . (substr($string, 1, strlen($string)));
$string = substr($string, 0, strlen($string) - 1);
$string = $string . $a;
return ucfirst(strtolower($string));
}
Having strings like
$s1 = "Elegan-71";
$s2 = "DganSD-171";
$s2 = "SD-1";
what would be the best way to delete all chars from '-' to end like
$cleans1 = "Elegan";
$cleans2 = "DganSD";
$cleans2 = "SD";
There is substr($s1, "-",4);
substr(string $string, int $start, int[optional] $length=null);
but how to tell that it should remove all numbers and how to know numbers size as they are variable?
list($cleans1) = explode("-",$s1,2);
This will do what you want:
<?php
$my_string = "happy-123";
$hyphen_position = strrpos($my_string, '-');
$fixed_string = substr($my_string, 0, $hyphen_position);
echo $fixed_string;
?>
$s1 = "Elegan-71";
if (strrpos($s1, '-')){
$cleans1 = substr($s1, 0, strrpos($s1, '-'));
}else{
$cleans1 = $s1;
}
That should do the trick.
Assuming you are cleaning each string individually, and you don't want to end up with neither an array or a list, and that each string ends up in that pattern (dash and number), this should do the trick:
$cleans1 = preg_replace('/-\d+$/', '', $s1);
ststr can does it too.
$s1 = "Elegan-71";
$clean = strstr($s1, '-', true);
echo $clean;
i like :
$cleans1 = strtok($s1, "-");
about strtok
Is there a PHP function that can extract a phrase between 2 different characters in a string? Something like substr();
Example:
$String = "[modid=256]";
$First = "=";
$Second = "]";
$id = substr($string, $First, $Second);
Thus $id would be 256
Any help would be appreciated :)
use this code
$input = "[modid=256]";
preg_match('~=(.*?)]~', $input, $output);
echo $output[1]; // 256
working example http://codepad.viper-7.com/0eD2ns
Use:
<?php
$str = "[modid=256]";
$from = "=";
$to = "]";
echo getStringBetween($str,$from,$to);
function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
?>
$String = "[modid=256]";
$First = "=";
$Second = "]";
$Firstpos=strpos($String, $First);
$Secondpos=strpos($String, $Second);
$id = substr($String , $Firstpos, $Secondpos);
If you don't want to use reqular expresion, use strstr, trim and strrev functions:
// Require PHP 5.3 and higher
$id = trim(strstr(strstr($String, '='), ']', true), '=]');
// Any PHP version
$id = trim(strrev(strstr(strrev((strstr($String, '='))), ']')), '=]');
Regular Expression is your friend.
preg_match("/=(\d+)\]/", $String, $matches);
var_dump($matches);
This will match any number, for other values you will have to adapt it.
You can use a regular expression:
<?php
$string = "[modid=256][modid=345]";
preg_match_all("/\[modid=([0-9]+)\]/", $string, $matches);
$modids = $matches[1];
foreach( $modids as $modid )
echo "$modid\n";
http://eval.in/9913
$str = "[modid=256]";
preg_match('/\[modid=(?P<modId>\d+)\]/', $str, $matches);
echo $matches['modId'];
I think this is the way to get your string:
<?php
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = '.layout {
color: {{ base_color }}
}
li {
color: {{ sub_color }}
}
.text {
color: {{ txt_color }}
}
.btn {
color: {{ btn_color }}
}
.more_text{
color:{{more_color}}
}';
$parsed = get_string_between($fullstring, '{{', '}}');
echo $parsed;
?>
(moved from comment because formating is easier here)
might be a lazy approach, but in such cases i usually would first explode my string like this:
$string_array = explode("=",$String);
and in a second step i would get rid of that "]" maybe through rtrim:
$id = rtrim($string_array[1], "]");
...but this will only work if the structure is always exactly the same...
-cheers-
ps: shouldn't it actually be $String = "[modid=256]"; ?
Try Regular Expression
$String =" [modid=256]";
$result=preg_match_all('/(?<=(=))(\d+)/',$String,$matches);
print_r($matches[0]);
Output
Array ( [0] => 256 )
DEMO
Explanation
Here its used the Positive Look behind (?<=)in regular expression
eg (?<=foo)bar matches bar when preceded by foo,
here (?<=(=))(\d+) we match the (\d+) just after the '=' sign.
\d Matches any digit character (0-9).
+ Matches 1 or more of the preceeding token
You can use a regular expression or you can try this:
$String = "[modid=256]";
$First = "=";
$Second = "]";
$posFirst = strpos($String, $First); //Only return first match
$posSecond = strpos($String, $Second); //Only return first match
if($posFirst !== false && $posSecond !== false && $posFirst < $posSecond){
$id = substr($string, $First, $Second);
}else{
//Not match $First or $Second
}
You should read about substr. The best way for this is a regular expression.
I have a string like this:
$string = "1,4|2,64|3,0|4,18|";
Which is the easiest way to access a number after a comma?
For example, if I have:
$whichOne = 2;
If whichOne is equal to 2, then I want to put 64 in a string, and add a number to it, and then put it back again where it belongs (next to 2,)
Hope you understand!
genesis'es answer with modification
$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
//do whatever you want here
//for example:
$numbers[1] += 100; // 100 + 64 = 164
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
if ($v) {
$ex = explode(',', $v);
$values[$ex[0]] = $ex[1];
}
}
To find the value of say, 2, you can use $whichOne = $values[2];, which is 64
I think it is much better to use the foreach like everyone else has suggested, but you could do it like the below:
$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";
echo "Starting String: $string <br>";
$pos = strpos($string, $whichOne);
//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);
$tempstring = explode("|", $valuepos);
$value = $tempstring[0]; //This will ow be 64
$newValue = $value + 18;
//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;
$string = str_replace($replaceValue, $newValue, $string);
echo "Ending String: $string";
This results in:
Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|
You could run into issues if there is more than one index of 2... this will only work with the first instance of 2.
Hope this helps!
I know this question is already answered, but I did one-line solution (and maybe it's faster, too):
$string = "1,4|2,64|3,0|4,18|";
$whichOne = 2;
$increment = 100;
echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);
Example run in a console:
noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|
See http://us.php.net/manual/en/function.preg-replace.php