remove front and last of the character of a string in php - php

My goal is to create a function that removes the first and last characters of a string in php.
My code:
function remove_char(string $s): string {
$len = strlen($s);
return substr($s,1,$len-2);
}
This not past the codewar code test. Can anyone tell me why it is not correct?

The built in function substr is accepting negative value, when you use negative value it affect readability. You can also give the function name better and clearer name like so:
function modify_string(string $s): string {
return substr($s, 1, -1);
}

try this code.
function remove_char(string $s){
if(strlen($s) > 1){
return substr($s, 1, -1);
}
return false;
}

<?php
function remove($word){
$result = substr($word, 1, -1);
return $result;
}
$word = 'HELLO';
$results = remove($word);
echo $results;
?>
Demo

Related

Extract a particular string form a long string in php

I have this string "PAX 098-5503268037/ETAI/USD107.75/15MAY20/KTMVS31KL/10303171" and would like to extract the USD107.75.I have this function:
Here:
$str = PAX 098-5503268037/ETAI/USD107.75/15MAY20/KTMVS31KL/10303171;
$from = '/ETAI';
$to = '/';
public function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
The function only return an empty string.
What am I missing?
Thanks
If you do a bit of debugging...
public function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
echo $sub.PHP_EOL;
return substr($sub,0,strpos($sub,$to));
}
you will see the interim output is
/USD107.75/15MAY20/KTMVS31KL/10303171
as you then look for the first / and extract up to that, that is the first character.
A simple solution to what you already have is to add +1 in the start position...
public function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from)+1,strlen($str));
return substr($sub,0,strpos($sub,$to));
}
Alternatively, you can as u_mulder indicated, explode() on / and then extract the part you are after...
echo explode("/", $str)[2];

I want to convert alphabets to numbers, in this way: A=0, B=1, C=2... Z=25 using php

I want to write a function that take input as a string and convert alphabets to number and returns the converted numbers, in this way: A(a)=1, B(b)=2, C(c)=3... Z(z)=25 using php
thanks in advance
First, we make everything lowercase.
Then, using the ord function, we get the ascii code, and then substract 'a' from it.
function one_char_map($chr)
{
$chr=strtolower($chr);
return ord($chr)-ord('a');
}
function string_map($str)
{
return implode(array_map('one_char_map',str_split($str)));
}
echo string_map('abcD');//0123
Please try this :
function conv($alph=null){
return (!is_null($alph)?strpos("abcdefghijklmnopqrstuvwxyz", $alph):"Need String");
}
echo "<br /><br />";
echo conv("a");
EDIT :
$str = "abcDefghZ";
$out = "";
for($i=0;$i<strlen($str);$i++){
$out .= conv(strtolower($str[$i]));
}
echo $str."<br />".$out;
If you trying to roll your own hash function: DONT.
If you need to accept other characters from ASCII, use PHP's ord() function.
Try this:
This function returns the position, and optionally accepts a base integer to shift the numbers if you need to.
function alpha_ord($str, $base = 0) {
$pos = stripos(
'abcdefghijklmnopqrstuvwxyz',
$str{0}
);
if ($pos !== FALSE) {
$pos += $base;
}
return $pos;
}
print alpha_ord('A'); // 0
print alpha_ord('Z', 1); // 26
print alpha_ord('Z'); // 25
print alpha_ord('A', 65); // 65

preg_replace to match all but first occurance of something?

I'm looking for a way to replace all but first occurrences of a group or some character.
For example a following random string:
+Z1A124B555ND124AB+A555
1,5,2,4,A,B and + are repeating through out the string.
124, 555 are groups of characters that are also reoccurring.
Now, let's say I want to remove every but first occurrence of 555, A and B.
What regex would be appropriate? I could think of an example replacing all:
preg_replace('/555|A|B/','',$string);
Something like ^ that, but I want to keep the first occurrence... Any ideas?
Are your strings always delimited by plus signs? Do 555, A, and B always occur in the first "group" (delimited by +)?
If so, you can split, replace and then join:
$input = '+Z1A124B555+A124AB+A555';
$array = explode('+', $input, 3); // max 3 elements
$array[2] = str_replace(array('555', 'A', 'B'), '', $array[2]);
$output = implode('+', $array);
ps. No need to use regexes, when we can use a simple str_replace
Use the preg_replace_callback function:
$replaced = array('555' => 0, 'A' => 0, 'B' => 0);
$input = '+Z1A124B555+A124AB+A555';
$output = preg_replace_callback('/555|[AB]/', function($matches) {
static $replaced = 0;
if($replaced++ == 0) return $matches[0];
return '';
}, $input);
This solution could be modified to do what you want: PHP: preg_replace (x) occurrence?
Here is a modified solution for you:
<?php
class Parser {
private $i;
public function parse($source) {
$this->i=array();
return preg_replace_callback('/555|A|B/', array($this, 'on_match'), $source);
}
private function on_match($m) {
$first=$m[0];
if(!isset($this->i[$first]))
{
echo "I'm HERE";
$this->i[$first]=1;
}
else
{
$this->i[$first]++;
}
// Return what you want the replacement to be.
if($this->i[$first]>1)
{
$result="";
}
else
{
$result=$m[0];
}
return $result;
}
}
$sample = '+Z1A124B555ND124AB+A555';
$parse = new Parser();
$result = $parse->parse($sample);
echo "Result is: [$result]\n";
?>
A more generic function that works with every pattern.
function replaceAllButFirst($pattern, $replacement, $subject) {
return preg_replace_callback($pattern,
function($matches) use ($replacement, $subject) {
static $s;
$s++;
return ($s <= 1) ? $matches[0] : $replacement;
},
$subject
);
}

Find the position of the first occurrence of any number in string

Can someone help me with algorithm for finding the position of the first occurrence of any number in a string?
The code I found on the web does not work:
function my_offset($text){
preg_match('/^[^\-]*-\D*/', $text, $m);
return strlen($m[0]);
}
echo my_offset('[HorribleSubs] Bleach - 311 [720p].mkv');
The built-in PHP function strcspn() will do the same as the function in Stanislav Shabalin's answer when used like so:
strcspn( $str , '0123456789' )
Examples:
echo strcspn( 'That will be $2.95 with a coupon.' , '0123456789' ); // 14
echo strcspn( '12 people said yes' , '0123456789' ); // 0
echo strcspn( 'You are number one!' , '0123456789' ); // 19
HTH
function my_offset($text) {
preg_match('/\d/', $text, $m, PREG_OFFSET_CAPTURE);
if (sizeof($m))
return $m[0][1]; // 24 in your example
// return anything you need for the case when there's no numbers in the string
return strlen($text);
}
function my_ofset($text){
preg_match('/^\D*(?=\d)/', $text, $m);
return isset($m[0]) ? strlen($m[0]) : false;
}
should work for this. The original code required a - to come before the first number, perhaps that was the problem?
I can do regular expressions but I have to go into an altered state to
remember what it does after I've coded it.
Here is a simple PHP function you can use...
function findFirstNum($myString) {
$slength = strlen($myString);
for ($index = 0; $index < $slength; $index++)
{
$char = substr($myString, $index, 1);
if (is_numeric($char))
{
return $index;
}
}
return 0; //no numbers found
}
Problem
Find the first occurring number in a string
Solution
Here is a non regex solution in javascript
var findFirstNum = function(str) {
let i = 0;
let result = "";
let value;
while (i<str.length) {
if(!isNaN(parseInt(str[i]))) {
if (str[i-1] === "-") {
result = "-";
}
while (!isNaN(parseInt(str[i])) && i<str.length) {
result = result + str[i];
i++;
}
break;
}
i++;
}
return parseInt(result);
};
Example Input
findFirstNum("words and -987 555");
Output
-987

built in function to combine overlapping string sequences in php?

Is there a built in function in PHP that would combine 2 strings into 1?
Example:
$string1 = 'abcde';
$string2 = 'cdefg';
Combine to get: abcdefg.
If the exact overlapping sequence and the position are known, then it is possible to write a code to merge them.
TIA
I found the substr_replace method to return funny results.
Especially when working with url strings. I just wrote this function.
It seems to be working perfectly for my needs.
The function will return the longest possible match by default.
function findOverlap($str1, $str2){
$return = array();
$sl1 = strlen($str1);
$sl2 = strlen($str2);
$max = $sl1>$sl2?$sl2:$sl1;
$i=1;
while($i<=$max){
$s1 = substr($str1, -$i);
$s2 = substr($str2, 0, $i);
if($s1 == $s2){
$return[] = $s1;
}
$i++;
}
if(!empty($return)){
return $return;
}
return false;
}
function replaceOverlap($str1, $str2, $length = "long"){
if($overlap = findOverlap($str1, $str2)){
switch($length){
case "short":
$overlap = $overlap[0];
break;
case "long":
default:
$overlap = $overlap[count($overlap)-1];
break;
}
$str1 = substr($str1, 0, -strlen($overlap));
$str2 = substr($str2, strlen($overlap));
return $str1.$overlap.$str2;
}
return false;
}
Usage to get the maximum length match:
echo replaceOverlap("abxcdex", "xcdexfg"); //Result: abxcdexfg
To get the first match instead of the last match call the function like this:
echo replaceOverlap("abxcdex", "xcdexfg", “short”); //Result: abxcdexcdexfg
To get the overlapping string just call:
echo findOverlap("abxcdex", "xcdexfg"); //Result: array( 0 => "x", 1 => "xcdex" )
It's possible using substr_replace() and strcspn():
$string1 = 'abcde';
$string2 = 'cdefgh';
echo substr_replace($string1, $string2, strcspn($string1, $string2)); // abcdefgh
No, there is no builtin function, but you can easily write one yourself by using substr and a loop to see how much of the strings that overlap.

Categories