1

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

1 Answer 1

1

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]+)[^\]]*\]/
Sign up to request clarification or add additional context in comments.

2 Comments

Amazing. Could I possibly ask a secondary... What if the last space is missing and could only be a ']' so space/] to test against ?
Many thanks for this. Makes large forms in contactForm7 a breeze when having to format the email out... now I can just copy the form itself. Best

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.