src/MultiStringReplacer.php
/**
	 * Search and replace a set of keywords in some text.
	 *
	 * @param string $text The string to search in.
	 * @return string The input text with replacements.
	 *
	 * @par Example:
	 * @code
	 *   $replacer = new MultiStringReplacer( array( 'csh' => 'sea shells' ) );
	 *   $replacer->searchAndReplace( 'She sells csh by the sea shore.' );
	 *   // result: 'She sells sea shells by the sea shore.'
	 * @endcode
	 */
Search and replace a set of keywords in some text.
@param string $text The string to search in.
@return string The input text with replacements.


Search and replace a set of keywords in some text . @param string $text The string to search in . @return string The input text with replacements .
public function searchAndReplace( $text ) {
		$state = 0;
		$length = strlen( $text );
		$matches = [];
		for ( $i = 0; $i < $length; $i++ ) {
			$ch = $text[$i];
			$state = $this->nextState( $state, $ch );
			foreach ( $this->outputs[$state] as $match ) {
				$offset = $i - $this->searchKeywords[$match] + 1;
				$matches[$offset] = $match;
			}
		}
		ksort( $matches );
		$buf = '';
		$lastInsert = 0;
		foreach ( $matches as $offset => $match ) {
			if ( $offset >= $lastInsert ) {
				$buf .= substr( $text, $lastInsert, $offset - $lastInsert );
				$buf .= $this->replacePairs[$match];
				$lastInsert = $offset + $this->searchKeywords[$match];
			}
		}
		$buf .= substr( $text, $lastInsert );
		return $buf;
	}
public function searchAndReplace ( $ text ) { $ state = 0 ; $ length = strlen ( $ text ) ; $ matches = [ ] ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ ch = $ text [ $ i ] ; $ state = $ this -> nextState ( $ state , $ ch ) ; foreach ( $ this -> outputs [ $ state ] as $ match ) { $ offset = $ i - $ this -> searchKeywords [ $ match ] + 1 ; $ matches [ $ offset ] = $ match ; } } ksort ( $ matches ) ; $ buf = '' ; $ lastInsert = 0 ; foreach ( $ matches as $ offset => $ match ) { if ( $ offset >= $ lastInsert ) { $ buf .= substr ( $ text , $ lastInsert , $ offset - $ lastInsert ) ; $ buf .= $ this -> replacePairs [ $ match ] ; $ lastInsert = $ offset + $ this -> searchKeywords [ $ match ] ; } } $ buf .= substr ( $ text , $ lastInsert ) ; return $ buf ; }
Search and replace a set of keywords in some text.
Search and replace a set of keywords in some text .