user3016473 user3016473 - 1 year ago 73
PHP Question

PHP Regex find + alter + replace within each tag

I am new to regex if this is indeed what I need.

The string might include :

[name* your-name ]

[email* your-main-email some_thing]


Amateur logic :

  1. Search string for '['

  2. get substring between this and next ']'

  3. extract hyphenated word (probably find first word between first and next space)

  4. Replace substring with hyphenated word

  5. Repeat with all remaining tags

To hopefully produce :




Or am I off target with method?

Many thanks

Answer Source

Try this code

$str = '[name* your-name ] [email* your-main-email some_thing]';
$str = preg_replace("/\[[^\s]+\s+([^\]\s]+)\s+[^\]]*\]/", "[$1]", $str);
echo $str;

Regex explanation:

  • / Delimiter
  • \[ Match starting square bracket
  • [^\s]+ Match one or more non-space character
  • \s+ Match one or more space
  • ( Start capturing group
  • [^\]\s]+ Match one or more character that is not space and not ]
  • ) End capturing group
  • \s+ Match one or more space
  • [^\]]* Match zero or more character that is not ]
  • \] Match closing square bracket
  • / Delimiter


To do replace when last space is missing i.e. [name* your-name] then use following regex

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download