PHP - 从文本中隔离第一个字母

I have a set of articles, in which I want to style the first letter from each article (with CSS).

the articles usually start with a paragrah, like:

<p> bla bla </p>

So how could I wrap the first letter from this text within a <span> tag ?

<?php

$str = '<p> bla bla </p>';
$search = '_^<p> *([\w])(.+) *</p>$_i';
$replacement = '<p><span>$1</span>$2</p>';

$new = preg_replace( $search, $replacement, $str );

echo $new."
";

You can do this in all CSS.

CSS supports "Pseudo-Elements" where you can choose the first letter / first word and format it differently from the rest of the document.

http://www.w3schools.com/CSS/CSS_pseudo_elements.asp

There's a compatibility chart; some of these may not work in IE 6

http://kimblim.dk/css-tests/selectors/

Unless you need to do something extremely fancy, there's also the :first-letter CSS selector.

you could add a Php span but might not be as clean $s = "

la la

"; $strip = trim(strip_tags($s)); $t = explode(' ', $strip); $first = $t[0];

// then replace first character with span around it $replace = preg_replace('/^?/', '$1', $first);

// then replace the first time of that word in the string $s = preg_replace('/'.$first.'/', $replace, $s, 1);

echo $s;

//not tested

I've not found a versatile method yet, but a traditional code implementation (that may be slower) works:

function pos_first_letter($haystack) {
  $ret = false;
  if (!empty($haystack)) {
    $l = strlen($haystack);
    $t = false;
    for ($i=0; $i < $l; $i++) {
      if (!$t && ($haystack[$i] == '<') ) $t = true;
      elseif ($t && ($haystack[$i] == '>')) $t = false;
      elseif (!$t && !ctype_space($haystack[$i])) {
        $ret = $i;
        break;
      }
    }
  }
  return $ret;
}

Then call:

$i = pos_first_letter( $your_string );
if ($i !== false) {
  $output = substr($s, 0, $i);
  $output .= '<span>' . substr($s, $i, 1) . '</span>';
  $output .= substr($s, $i+1);
}