php: parse string to get string - php

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

Related

how to remove same number in php?

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

PHP adding the value 1 to a position in an string and replace

I want to replace a letter with another character and also add 1 value more.
I mean the values are dynamic
For example I have H9 ,i want to replace as G10 .
Similarly...
H2 as G3
H6 as G7
Is it possible to use str_replace() for this ?
I got this one which works for me:
$old_string = "H2";
$new_string = "G" . (substr($old_string, 1) + 1);
echo $new_string;
Works fine for me. This is just for one value, but i guess you can loop through an array too, just have to modify the values like this
foreach($old_values as $v) {
$new_values[] = "G" . (substr($v, 1) + 1);
}
So you could save all the values into the $new_string array
Try This
<?php
$str = "H25";
preg_match_all('!\d+!', $str, $matches);
$str = str_replace($matches['0']['0'], $matches['0']['0']+1, $str, $count);
echo $str;
?>
Of course you can use str_replace()
Use
$new = array("G10", "G3", "G7");
$old = array("H9", "H2", "H6");
$string = str_replace($old, $new, $string);
where $string is your original string.
More simpler way... (Generalized Solution)
<?php
$str='G10';
preg_match('!\d+!', $str, $digit); //<---- Match the number
$str = substr($str,0,1); //<--- Grab the first char & increment it in the second line
echo ++$str.($digit[0]+1); //"prints" H11
Demo

Removing last part of string divided by a colon

I have a string that looks a little like this, world:region:bash
It divides folder names, so i can create a path for FTP functions.
However, i need at some points to be able to remove the last part of the string, so, for example
I have this world:region:bash
I need to get this world:region
The script wont be able to know what the folder names are, so some how it needs to be able to remove the string after the last colon.
$res=substr($input,0,strrpos($input,':'));
I should probably highlight that strrpos not strpos finds last occurrence of a substring in given string
$tokens = explode(':', $string); // split string on :
array_pop($tokens); // get rid of last element
$newString = implode(':', $tokens); // wrap back
You may want to try something like this:
<?php
$variable = "world:region:bash";
$colpos = strrpos($variable, ":");
$result = substr($variable, 0, $colpos);
echo $result;
?>
Or... if you create a function using this information, you get this:
<?php
function StrRemoveLastPart($string, $delimiter)
{
$lastdelpos = strrpos($string, $delimiter);
$result = substr($string, 0, $lastdelpos);
return $result;
}
$variable = "world:region:bash";
$result = StrRemoveLastPart($variable, ":");
?>
Explode the string, and remove the last element.
If you need the string again, use implode.
$items = array_pop(explode(':', $the_path));
$shotpath = implode(':', $items);
Use regular expression /:[^:]+$/, preg_replace
$s = "world:region:bash";
$p = "/:[^:]+$/";
$r = '';
echo preg_replace($p, $r, $s);
demo
Notice how $ which means string termination, is made use of.
<?php
$string = 'world:region:bash';
$string = implode(':', explode(':', $string, -1));

Getting value after second - in php

I have E-20-99 in a string i want to get last value 99 and add 1 means 100 and then wants to generate new string E-20-100.
If your string ALWAYS looks like this, you can easily break it without a regex, simply by using explode()
$string = "E-20-99";
$parts = explode('-', $string);
$last_part = $parts[2] + 1;
$parts[2] = $last_part;
$string = implode('-', $parts);
echo $string;
If the string is always E-20-XX you can use
$n = ((int)substr('E-20-99', strlen('E-20-')))+1;
echo 'E-20-' . $n;
If the string might vary a bit more you could use a regualar expressions such as:
$string = 'E-20-99';
preg_match('/(E-\d+-)(\d+)/', $string, $match);
echo $match[1] . ((int)$match[2] + 1);
$old_str = 'E-20-99';
$new_str = preg_replace_callback('/(?<=-)\d+$/', function($matches) {
return $matches[0] + 1;
}, $old_str);

PHP preg_replace

*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);

Categories