Skip to content

Instantly share code, notes, and snippets.

@Phoenix2k
Created June 20, 2018 19:20
Show Gist options
  • Save Phoenix2k/003a30d7f648a0cfec7c30825dab1003 to your computer and use it in GitHub Desktop.
Save Phoenix2k/003a30d7f648a0cfec7c30825dab1003 to your computer and use it in GitHub Desktop.
PHP: Search and replace function
<?php
/**
* Search and replaces text.
*
* @param String $text Text to be replaced
* @param Array $args Key value pairs representing search and replace respectively
* @return String Text with search and replace applied.
*/
function search_and_replace( $text = '', $args = [ ] ) {
if ( empty( $args ) || ! array( $args ) ) return $text;
foreach ( $args as $search => $replace ) {
if ( false !== strpos( $text, $search ) ) {
$text = str_replace( $search, $replace, $text );
}
}
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment