开发者

Time-saving string manipulation for lists PHP-

开发者 https://www.devze.com 2023-02-18 01:44 出处:网络
I need to format users input for price lists, and would like to achieve this without using multiple form fields. If the user creates a list, for example:

I need to format users input for price lists, and would like to achieve this without using multiple form fields. If the user creates a list, for example:

  Eye Treatments<br />
  Eyebrow Tint $10<br />
  Eyelash Tint $15<br />
  Eyelash Extensions (brunched) Full Set $50
  <br /><br />  

How can I format it like this?

<b>Eye Treatments</b>
 <ul>
 <li>Eyebrow Tint <span>$10</span></li>
 <li>Eyelash Tint <span>$15</span></li>
 <li>Eyelash Extensions<i>(brunched)</i> Full Set <span>$50</span></li>
 </ul>

Thanks for reading. Any help is appreci开发者_Python百科ated. Lea


Input

Eye Treatments<br />
  Eyebrow Tint $10<br />
  Eyelash Tint $15<br />
  Eyelash Extensions (brunched) Full Set $50
  <br /><br />

PHP

$lines = explode('<br />', $str);
$lines = array_map('trim', $lines);

$newStr = '<b>' .  array_shift($lines) . '</b>' . "\n<ul>";

foreach($lines as $line) {
    if (empty($line)) {
        continue;
    }

    preg_match_all('/^(?P<product>.*?) (?P<price>\$\d+)$/', $line, $matches);
    $newStr .= '<li>' . preg_replace('/\(.*?\)/', '<i>$0</i>', $matches['product'][0]) . ' <span>'  . $matches['price'][0] . '</span></li>' . "\n";
}

$newStr .= '</ul>';
echo $newStr;

See it.

Output

<b>Eye Treatments</b> 
<ul><li>Eyebrow Tint <span>$10</span></li> 
<li>Eyelash Tint <span>$15</span></li> 
<li>Eyelash Extensions <i>(brunched)</i> Full Set <span>$50</span></li> 
</ul>

Assumptions

  • That the br actually are br elements, most likely they are \n (replace '<br />' with "\n" if they are).
  • Your string always looks like your example, and it is not embedded in other HTML.
  • Your prices don't contain a decimal - it is trivial to add it, however.

Recommendations

  • This method is flaky because it is very susceptible to being broken by an invalid pattern.
  • Should that first b element really be a h3 or something?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号