1

I have a task to find and replace words starting and ending with "#".

Example - my string will look like:

Put your hands up in the air for #performer1# , Put your hands up in the air for #event#.

What I expect as a output is:

Put your hands up in the air for #performer1# , Put your hands up in the air for #event#.

I have no idea about regular expressions in php, and I'm a beginner, can someone help?

1 Answer 1

2

As you already suggested, the preg_replace function should do the trick. What you now need is a regular expression like this

$string = "Put your hands up in the air for #performer#, ...";
$pattern = "/#(\w+)#/";
$replacement = '<strong>$1</strong>';
$new_string = preg_replace($pattern, $replacement, $string);

The magic bit is the $pattern variable where you specify what to look for. If you put parenthesis around something, you can reference the actual contents in the $replacement variable.

The \w+ basically says: match as many characters as possible (and at least one) that are either a-z, A-Z, 0-9 or _.

The PHP PCRE Pattern Syntax can give you some more hints about how to use regular expressions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.