简体   繁体   English

如何显示div中字符串中的前两个单词并保留在其他span php中?

[英]How to display first two words from string in div and remaining in other span php?

I want to display string in different div and span, but can't able to do that. 我想在不同的div和span中显示字符串,但是无法做到这一点。 I am using below code to do that, but it not works. 我正在使用下面的代码来做到这一点,但它不起作用。 Can anyone help me solve out problem? 谁能帮我解决问题?

Want to display like this: 想要这样显示:

Input String: Lorem ispum dolor text si sample dummy text. 输入字符串:Lorem ispum dolor文本si示例虚拟文本。

Output: Lorem ispum <span> dolor text si sample dummy text.</span> 输出:Lorem ispum <span> dolor文本si示例虚拟文本。</ span>

if(!empty($extraData['heading_text']) && str_word_count($extraData['heading_text']) >= 3) :
  $getwords = explode(" ", $extraData['heading_text']);
  echo $getwords[0].' '.$getwords[1] .' '.'<span>'.$getwords[2]. '</span>';
  unset($getwords[0]);
  unset($getwords[1]);
  unset($getwords[2]);
  echo  implode(" ", array_values($getwords));
else :
  echo $extraData['heading_text']; 
endif;

Well, just extract and output the tokens you are interested in: 好吧,只需提取并输出您感兴趣的令牌:

<?php  
$input = "Lorem ispum dolor text si sample dummy text.";
preg_match('/^(\w+\s+\w+)\s+(.*)$/', $input, $token);
echo sprintf("<div>%s</div>\n<span>%s</span>\n", $token[1], $token[2]);

The output obviously is: 输出显然是:

<div>Lorem ispum</div>
<span>dolor text si sample dummy text.</span>

The same certainly is possible using explode() too, but much more complex: 当然也可以使用explode() ,但是要复杂得多:

<?php
$input = "Lorem ispum dolor text si sample dummy text.";
$word = explode(" ", $input);
echo sprintf("<div>%s %s</div>\n", $word[0], $word[1]);
unset($word[0]); 
unset($word[1]);
echo sprintf("<span>%s</span>\n", implode(" ", $word));

UPDATE: 更新:

The first alternative, based on a regular expression, only works for true "words", that is defined pretty strict. 第一种选择基于正则表达式,仅适用于定义严格的真正“单词”。 You can somewhat "weaker" that strict behavior by slightly altering the expression: 您可以通过稍微更改表达式来“减弱”严格的行为:

<?php  
$input = "What we've Done";
preg_match('/^([^\s]+\s+[^\s]+)\s+(.*)$/', $input, $token);
echo sprintf("<div>%s</div>\n<span>%s</span>\n", $token[1], $token[2]);

With that modification the output again is as expected: 经过修改,输出再次如期:

<div>What we've</div>
<span>Done</span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM