user3016473 user3016473 - 1 month ago 4
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]

etc


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 :

[your-name]

[your-main-email]

etc


Or am I off target with method?

Many thanks

Answer

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

Edit

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

/\[[^\s]+\s+([^\]\s]+)[^\]]*\]/
Comments