Skip to content

Instantly share code, notes, and snippets.

@nhalstead
Last active June 25, 2020 18:27
Show Gist options
  • Save nhalstead/816e610c931586857bc33751a81eae2d to your computer and use it in GitHub Desktop.
Save nhalstead/816e610c931586857bc33751a81eae2d to your computer and use it in GitHub Desktop.
String Helpers to insert text inline with simple and easy methods.
<?php
/**
* Helper Function to insert text after a set string is found.
* Insert Text from the head of the string After the Needle
*
* @param string $haystack
* @param string $needle
* @param string $insertText
* @return string
*/
function insertHeadAfter(string $haystack, string $needle, string $insertText) {
// Find the FIRST occurrence of the Needle in the Given Haystack
$pos = strpos($haystack, $needle) + strlen($needle);
if($pos === false) return $haystack;
// Grab all of the Text from the start to the end of the needle
$output = substr($haystack, 0, $pos);
// Insert Text
$output .= $insertText;
// Add the rest of the string
$output .= substr($haystack, $pos);
return $output;
}
/**
* Helper Function to insert text before a set string is found at the end of the string.
* Insert Text from the tail of the string Before the Needle
*
* @param string $haystack
* @param string $needle
* @param string $insertText
* @return string
*/
function insertTailBefore(string $haystack, string $needle, string $insertText) {
// Find the LAST occurrence of the Needle in the Given Haystack
$pos = strrpos($haystack, $needle);
if($pos === false) return $haystack;
// Grab all of the Text from the start to the end of the needle
$output = substr($haystack, 0, $pos);
// Insert Text
$output .= $insertText;
// Add the rest of the string
$output .= substr($haystack, $pos);
return $output;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment