Ask Your Question
4

How can I use PHP Regex to substitute a string with an array of words that have to begin and end with hyphens or spaces?

asked 2022-06-04 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-10-23 17:00:00 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-04 11:00:00 +0000

Seen: 9 times

Last updated: Oct 23 '21