I have a string
$initial_string = "<input type = 'checkbox' name = 'cb[]' value = '[a-zA-Z]'>"

In this I want to match the letters 'cb' and replace it with '1cb'.
The final string should look like this
$final_string = "<input type = 'checkbox' name = '1cb[]' value = '[a-zA-Z]'>"

My code is as follows. But nothing works. I have tried all tricks. Help will be greatly appreciated.

if (preg_match("cb", $initial_string))
{
$pattern = "cb";
$pat = "1cb";
$replacement =  "$pat";
$final_string = preg_replace($pattern, $replacement, $initial_string);
echo "$final_string";
}

Recommended Answers

All 2 Replies

The $pattern must be a regular expression. It must have delimiters around the pattern, and optional modifiers after the second delimiter.

Example patterns:

"/cb/" - matches cb
"/cb/i" - matches upper and lower case cb

see the docs for preg_match. http://php.net/preg_match

The $pattern must be a regular expression. It must have delimiters around the pattern, and optional modifiers after the second delimiter.

Example patterns:

"/cb/" - matches cb
"/cb/i" - matches upper and lower case cb

see the docs for preg_match. http://php.net/preg_match

Thanks.It worked like charm

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.