Skip to content

Instantly share code, notes, and snippets.

@Steveorevo
Last active February 9, 2023 19:12
Show Gist options
  • Save Steveorevo/43d3bb5d66e138802b1a1c249c00bb57 to your computer and use it in GitHub Desktop.
Save Steveorevo/43d3bb5d66e138802b1a1c249c00bb57 to your computer and use it in GitHub Desktop.
Linear version of GStrings' most used parsing methods
<?php
/**
* Deletes the right most string from the found search string
* starting from right to left, including the search string itself.
*
* @return string
*/
function delRightMost( $sSource, $sSearch ) {
for ( $i = strlen( $sSource ); $i >= 0; $i = $i - 1 ) {
$f = strpos( $sSource, $sSearch, $i );
if ( $f !== false ) {
return substr( $sSource, 0, $f );
break;
}
}
return $sSource;
}
/**
* Deletes the left most string from the found search string
* starting from
*
* @return string
*/
function delLeftMost( $sSource, $sSearch ) {
for ( $i = 0; $i < strlen( $sSource ); $i = $i + 1 ) {
$f = strpos( $sSource, $sSearch, $i );
if ( $f !== false ) {
return substr( $sSource, $f + strlen( $sSearch ), strlen( $sSource ) );
break;
}
}
return $sSource;
}
/**
* Returns the right most string from the found search string
* starting from right to left, excluding the search string itself.
*
* @return string
*/
function getRightMost( $sSource, $sSearch ) {
for ( $i = strlen( $sSource ); $i >= 0; $i = $i - 1 ) {
$f = strpos( $sSource, $sSearch, $i );
if ( $f !== false ) {
return substr( $sSource, $f + strlen( $sSearch ), strlen( $sSource ) );
}
}
return $sSource;
}
/**
* Returns the left most string from the found search string
* starting from left to right, excluding the search string itself.
*
* @return string
*/
public function getLeftMost( $sSource, $sSearch ) {
for ( $i = 0; $i < strlen( $sSource ); $i = $i + 1 ) {
$f = strpos( $sSource, $sSearch, $i );
if ( $f !== false ) {
return substr( $sSource, 0, $f );
break;
}
}
return $sSource;
}
function replaceFirst( $haystack, $needle, $replace ) {
$pos = strpos( $haystack, $needle );
if ($pos !== false) {
$newstring = substr_replace( $haystack, $replace, $pos, strlen( $needle ) );
}else{
$newstring = $haystack;
}
return $newstring;
}
function replaceLast( $haystack, $needle, $replace ) {
$pos = strrpos( $haystack, $needle );
if ($pos !== false) {
$newstring = substr_replace( $haystack, $replace, $pos, strlen( $needle ) );
}else{
$newstring = $haystack;
}
return $newstring;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment