Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the PHP preg_replace() function to substitute a string with an array of words that begin and end with hyphens or spaces using the following regular expression:

/\b(word1|word2|word3)\b/

Here, \b represents a word boundary which will match the start or end of a word, and | represents a logical OR which will match any of the words in the array. For example, if you have an array $words = array('foo', 'bar', 'baz'); you can use the following code to replace all occurrences of these words within a string with an hyphen or space at the start and end:

$string = "foo bar baz";
$words = array('foo', 'bar', 'baz');
$replace = '-$0-';
$result = preg_replace('/\b(' . implode('|', $words) . ')\b/', $replace, $string);
echo $result;

In the above example, implode() is used to join the elements of the $words array with a | separator, which is then used inside the regular expression. The $0 in the $replace string represents the entire matching word. The resulting output will be:

-foo- -bar- -baz-

Note that if you want to use a different character than hyphen, you can change the $replace variable to use the desired character.