php:: apply backticks to first word in sentence
basically what I am trying to do is,
I have an array that looks something like this:
array(
a开发者_开发知识库rray(
'select' =>'first string',
'escape' => true
),
array(
'select' =>'second',
'escape' => true
),
array(
'select' =>'the third string',
'escape' => true
),
array(
'select' =>'fourth string',
'escape' => false
),
)
I am looping over it and I want to end up with this output
array(
array(
'select' =>'`first` string',
'escape' => true
),
array(
'select' =>'`second`',
'escape' => true
),
array(
'select' =>'`the` third string',
'escape' => true
),
array(
'select' =>'fourth string',
'escape' => false
),
)
so basic rules are
- backticks are only applied if escape is true
- backticks are only applied to the first word in a sentence
- if there is only one word backticks are applied to the word
My plan was to use
if($item['escape']) {
$pos = (strpos($item['select'], ' ') === false ? strlen($item['select']) : strpos($item['select'], ' '));
$item['select'] = '`' . substr($item['select'], 0, $pos) . '`' . substr($item['select'], $pos, strlen($item['select']));
}
but the $item['select'] =
line seems rather long winded, is there a better way to write it?
if($item['escape']) {
$item['select'] = explode(' ', $item['select']);
$item['select'][0] = '`'.$item['select'][0].'`';
$item['select'] = implode(' ', $item['select']);
}
should be good.
You could split $item['select']
on the space character:
if($item['escape']) {
$words = explode(' ', $item['select']);
$words[0] = "`{$words[0]}`";
$item['select'] = implode(' ', $words);
}
How about a regular expression?
$item['select'] = preg_replace( '/^(.*?)( |\z)(.*)/', '`$1`$2$3' , $item['select']);
It's short and its intent clear.
Edited: didn't take into account the case where there is only one word (it doesn't look very simple now...)
You can use regex as:
foreach($input as $key => &$val) {
if($val['escape']) {
$val['select'] = preg_replace('/^(\w+)/','`$1`',$val['select']);
}
}
See it
精彩评论