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.
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
Asked: 2022-06-04 11:00:00 +0000
Seen: 7 times
Last updated: Oct 23 '21
How can a HTTP header be inserted in WordPress?
How can data be stored in a data attribute and utilized through Ajax?
How can an array be passed using typo3 flexform xml and itemsProcConfig?
Does JSON encode fail to retrieve data from the database?
Can the GS1 128 barcode decoder in PHP or Jquery be utilized?
How can Xdebug be used in conjunction with VSCode for Laravel on Sail and WSL2?
In PHP, what is the method for finding encrypted data using the "like" operator?
What is the method to pass a variable from PHP back to JavaScript?
Why do PHP variable variables display unexpected behavior when used with arrays?