Smarty中常用变量操作符汇总,smarty操作符汇总_PHP教程
Smarty中常用变量操作符汇总,smarty操作符汇总
本文汇总了Smarty中常用变量操作符,分享给大家供大家参考。具体如下:
php模板引擎smarty的变量操作符可用于操作变量,自定义函数和字符。
语法中使用"|"应用变量操作符,多个参数用":"??指簟?/DIV>
capitalize[首字母大写]
count_characters[计算字符数]
cat[连接字符串]
count_paragraphs[计算段落数]
count_sentences[计算句数]
count_words[计算词数]
date_format[时间格式]
default[默认]
escape[转码]
indent[缩进]
lower[小写 ]
nl2br[换行符替换成
]
regex_replace[正则替换]
replace[替换]
spacify[插空]
string_format[字符串格式化]
strip[去除(多余空格)]
strip_tags[去除html标签]
truncate[截取]
upper[大写]
wordwrap[行宽约束]
组合使用多个操作符
实例如下:
{$title|upper}
{* 取其前40个字符 *}
Topic: {$topic|truncate:40:"..."}
{* 格式化文字串 *}
{"now"|date_format:"%Y/%m/%d"}
{* 在自定义函数里应用调节器 *}
{mailto|upper address="main@cn-web.com"}
capitalize(首字母大写)
index.php页面如下:
$smarty->assign('articleTitle', 'Police begin campaign to rundown jaywalkers.');
$smarty->display('index.tpl');
index.tpl页面如下:
{$articleTitle|capitalize}
OUTPUT输出如下:
Police Begin Campaign To Rundown Jaywalkers.
count_characters(计算变量里的字符数)
index.php如下:
$smarty->assign('articleTitle', 'Cold Wave Linked to Temperatures.');
$smarty->display('index.tpl');
index.tpl页面如下:
{$articleTitle|count_characters}
OUTPUT输出如下:
Cold Wave Linked to Temperatures.
cat(连接字符串)
将cat里的值连接到给定的变量后面
index.php如下:
$smarty->assign('articleTitle', 'Psychics predict world didn't end');
$smarty->display('index.tpl');
index.tpl页面如下:
OUTPUT输出如下:
count_paragraphs(计算段数)
计算变量里的段落数量
index.php如下:
$smarty->assign('articleTitle', 'War Dims Hope for Peace. Child's Death Ruins Couple's Holiday.');
$smarty->display('index.tpl');
index.tpl模板页面如下:
{$articleTitle|count_paragraphs}
OUTPUT输出如下:
Man is Fatally Slain. Death Causes Loneliness, Feeling of Isolation.
2
count_sentences(计算句数)
计算变量里句子的数量
index.php如下:
$smarty->assign('articleTitle', 'Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe.');
$smarty->display('index.tpl');
index.tpl模板如下:
{$articleTitle|count_sentences}
OUTPUT输出如下:
2
count_words(计算词数)
计算变量里的词数
index.php如下:
$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
$smarty->display('index.tpl');
index.tpl模板如下:
{$articleTitle|count_words}
OUTPUT输出如下:
7
date_format(日期格式)
Parameter Position
参数位置 Type Required Default Description
1 string No %b %e, %Y This is the format for the outputted date.
输出字串的格式
2 string No n/a This is the default date if the input is empty.
输入为空时的默认设置
在给定的函数serftime();里格式日期和时间.
Unix或者mysql等的时间戳(parsable by strtotime)都可以传递到smarty.
设计者可以使用date_format完全控制日期格式.
如果传给date_format的数据是空的,将使用第二个参数作为时间格式
index.php如下:
$smarty->assign('yesterday', strtotime('-1 day'));
$smarty->display('index.tpl');
index.tpl:
{$smarty.now|date_format:"%A, %B %e, %Y"}
{$smarty.now|date_format:"%H:%M:%S"}
{$yesterday|date_format}
{$yesterday|date_format:"%A, %B %e, %Y"}
{$yesterday|date_format:"%H:%M:%S"}
OUTPUT输出如下:
Tuesday, February 6, 2001
14:33:00
Feb 5, 2001
Monday, February 5, 2001
14:33:00
default(默认)
Parameter Position Type Required Default Description
1 string No empty This is the default value to output if the variable is empty.
这是变量为空的时候的默认输出
为空变量设置一个默认值.
当变量为空或者未分配的时候,将由给定的默认值替代输出.
index.php如下:
$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
$smarty->display('index.tpl');
index.tpl模板:
{$myTitle|default:"no title"}
OUTPUT输出:
no title
escape(转码)
Parameter Position Type Required Possible Values Default Description
1 string No html,htmlall,url,quotes,hex,hexentity,javascript html This is the escape format to use.
用于html转码,url转码,在没有转码的变量上转换单引号,十六进制转码,十六进制美化,或者javascript转码.
默认是html转码
index.php如下:
$smarty->assign('articleTitle', "'Stiff Opposition Expected to Casketless Funeral Plan'");
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|escape}
{$articleTitle|escape:"html"} {* escapes & " ' *}
{$articleTitle|escape:"htmlall"} {* escapes ALL html entities *}
{$articleTitle|escape:"url"}
{$articleTitle|escape:"quotes"}
href="{$EmailAddress|escape:"hexentity"}mailto:{$EmailAddress|escape:"hex"}">{$EmailAddress|escape:"hexentity"}
OUTPUT输出:
'Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan'
'Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan'
'Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan'
'Stiff+Opposition+Expected+to+Casketless+Funeral+Plan'
'Stiff Opposition Expected to Casketless Funeral Plan'
href="bob@me.netmailto:%62%6f%62%40%6d%65%2e%6e%65%74">bob@me.net
indent(缩进)
Parameter Position Type Required Default Description
1 integer No 4 This determines how many characters to indent to.
2 string No (one space) This is the character used to indent with.
在每行缩进字符串,默认是4个字符(pear标准也是).
作为可选参数,你可以指定缩进字符数.
作为第二个可选参数,你可以指定缩进用什么字符代替
index.php如下:
$smarty->assign('articleTitle', 'NJ judge to rule on nude beach.');
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|indent}
{$articleTitle|indent:10}
{$articleTitle|indent:1:"t"}
OUTPUT输出:
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.
NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.
NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.
NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.
lower(小写)
将变量字符串小写
index.php如下:
$smarty->assign('articleTitle', 'Two Convicts Evade Noose, Jury Hung.');
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|lower}
OUTPUT输出:
two convicts evade noose, jury hung.
nl2br(换行符替换成
)
所有的换行符将被替换成
.同php的nl2br()函数一样.
index.php如下:
$smarty->assign('articleTitle', "Sun or rain expectedntoday, dark tonight");
$smarty->display('index.tpl');
index.tpl模板:
OUTPUT输出:
today, dark tonight
regex_replace(正则替换)
寻找和替换正则表达式 .
Parameter Position Type Required Default Description
1 string Yes n/a This is the regular expression to be replaced.
替换正则表达式.
2 string Yes n/a This is the string of text to replace with.
使用什么文本字串来替换
index.php如下:
$smarty->assign('articleTitle', "Infertility unlikely tonbe passed on, experts say.");
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle}
{$articleTitle|regex_replace:"/[rtn]/":" "}
OUTPUT输出:
be passed on, experts say.
Infertility unlikely to be passed on, experts say.
replace(替换)
简单的搜索和替换字符串
Parameter Position Type Required Default Description
1 string Yes n/a This is the string of text to be replaced.
将被替换的字符串
2 string Yes n/a This is the string of text to replace with.
用来替换的文本
index.php如下:
$smarty->assign('articleTitle', "Child's Stool Great for Use in Garden.");
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|replace:"Garden":"Vineyard"}
{$articleTitle|replace:" ":" "}
OUTPUT输出:
Child's Stool Great for Use in Vineyard.
Child's Stool Great for Use in Garden.
spacify
是一种在字符串的每个字符之间插入空格或者插入其他的字符(串).
index.php如下:
$smarty->assign('articleTitle', 'Something Went Wrong in Jet Crash, Experts Say.');
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|spacify}
{$articleTitle|spacify:"^^"}
OUTPUT输出:
S o m e t h i n g W e n t W r o n g i n J e t C r a s h , E x p e r t s S a y .
S^^o^^m^^e^^t^^h^^i^^n^^g^^ ^^W^^e^^n^^t^^ ^^W^^r^^o^^n^^g^^ ^^i^^n^^ ^^J^^e^^t^^ ^^C^^r^^a^^s^^h^^,^^ ^^E^^x^^p^^e^^r^^t^^s^^ ^^S^^a^^y^^.
string_format(字符串格式化)
Parameter Position Type Required Default Description
1 string Yes n/a This is what format to use. (sprintf)
使用的格式化方式
是一种格式化浮点数的方法.例如十进制数.使用sprintf语法格式化
index.php如下:
$smarty->assign('number', 23.5787446);
$smarty->display('index.tpl');
index.tpl模板:
{$number|string_format:"%.2f"}
{$number|string_format:"%d"}
OUTPUT输出:
23.58
24
strip(去除(多余空格)
替换所有重复的空格,换行和tab为单个.
index.php如下:
$smarty->assign('articleTitle', "Grandmother ofneight makest hole in one.");
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|strip}
{$articleTitle|strip:" "}
OUTPUT输出:
eight makes hole in one.
Grandmother of eight makes hole in one.
Grandmother of eight makes hole in one.
strip_tags(去除html标签)
去除在之间的所有标签,包括.
index.php如下:
$smarty->assign('articleTitle', "Blind Woman Gets New Kidney from Dad she Hasn't Seen in years.");
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|strip_tags}
OUTPUT输出:
Blind Woman Gets New Kidney from Dad she Hasn't Seen in years.
truncate(截取)
Parameter Position Type Required Default Description
1 integer No 80 This determines how many characters to truncate to.
指定截取多少字符
2 string No ... This is the text to append if truncation occurs.
截取后加在截取词后的字符串
3 boolean No false This determines whether or not to truncate at a word boundary (false), or at the exact character (true).
检查是否截取到词的边界
截取字符串开始的一段.默认是80个.
你可以指定第二个参数作为在截取的那段字符串后加上什么字符.
默认情况下,smarty会截取到一个词的末尾,
如果你想要精确的截取多少个字符,把第三个参数改为"true"
index.php如下:
$smarty->assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.');
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}
OUTPUT输出:
Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after...
Two Sisters Reunite after
Two Sisters Reunite after---
Two Sisters Reunite after Eigh
Two Sisters Reunite after E...
upper(大写 )
将变量改为大写
index.php如下:
$smarty->assign('articleTitle', "If Strike isn't Settled Quickly it may Last a While.");
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|upper}
OUTPUT输出:
IF STRIKE ISN'T SETTLED QUICKLY IT MAY LAST A WHILE.
wordwrap(行宽约束)
可以指定段落的宽度(也就是多少个字符一行,超过这个字符数换行).默认80.
第二个参数可选,可以指定在约束点使用什么字符(默认是换行符n).
默认情况下smarty将截取到词尾,你也可以指定精确截取多少个字符
Parameter Position Type Required Default Description
1 integer No 80 This determines how many columns to wrap to.
指 定段落(句子)的宽度
2 string No n This is the string used to wrap words with.
使用什么字符约束
3 boolean No false This determines whether or not to wrap at a word boundary (false), or at the exact character (true).
是否精确约束到字符
index.php如下:
$smarty->assign('articleTitle', "Blind woman gets new kidney from dad she hasn't seen in years.");
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|wordwrap:30}
{$articleTitle|wordwrap:20}
{$articleTitle|wordwrap:30:"
n"}
{$articleTitle|wordwrap:30:"n":true}
OUTPUT输出:
Blind woman gets new kidney
from dad she hasn't seen in
years.
Blind woman gets new
kidney from dad she
hasn't seen in
years.
Blind woman gets new kidney
from dad she hasn't seen in years.
Blind woman gets new kidney fr
om dad she hasn't seen in year
s.
组合使用多个操作符
可以在一个变量上应用操作符,它们将从左到右依次组合应用.多个操作符必须用"|"符号分开.
index.php页面如下:
$smarty->assign('articleTitle', 'Smokers are Productive, but Death Cuts Efficiency.');
$smarty->display('index.tpl');
index.tpl模板:
{$articleTitle|upper|spacify}
{$articleTitle|lower|spacify|truncate}
{$articleTitle|lower|truncate:30|spacify}
{$articleTitle|lower|spacify|truncate:30:". . ."}
OUTPUT输出:
S M O K E R S A R E P R O D U C T I V E , B U T D E A T H C U T S E F F I C I E N C Y .
s m o k e r s a r e p r o d u c t i v e , b u t d e a t h c u t s...
s m o k e r s a r e p r o d u c t i v e , b u t . . .
s m o k e r s a r e p. . .
希望本文所述对大家的PHP程序设计有所帮助。
就是这个方法。
试了一下这样可以:
(放在循环之外)
(循环之内递增)

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











'!' 기호를 사용하는 대부분의 Linux 명령 사용법은 셸마다 다를 수 있습니다. 내가 제공하는 예제는 일반적으로 bash 셸에서 사용되지만 일부 다른 Linux 셸에서는 구현이 다를 수도 있고 '!' 기호의 특정 용도를 전혀 지원하지 않을 수도 있습니다. Linux 명령에서 '!' 기호의 놀랍고 신비한 용도에 대해 살펴보겠습니다. 1. 명령 번호를 사용하여 기록에서 명령을 실행합니다. 여러분이 알지 못할 수도 있는 것은 명령 기록에서 명령(이미 실행된 명령)을 실행할 수 있다는 것입니다. 먼저 'history' 명령을 실행하여 명령 번호를 찾습니다. linuxmi@linuxmi:~/www.linuxmi.

오늘날 웹사이트 개발은 중요한 구성 요소 템플릿 엔진과 분리될 수 없습니다. 템플릿 엔진은 페이지 템플릿과 데이터를 결합하여 특정 형식의 HTML 코드를 생성하는 도구를 말합니다. 다양한 웹사이트 개발 프레임워크에서 템플릿 엔진은 코드 중복을 크게 줄이고 페이지의 역동성을 향상시킬 수 있기 때문에 필수적인 구성 요소입니다. 가장 일반적이고 널리 사용되는 템플릿 엔진 중 하나는 Smarty입니다. Smarty는 DSL(DomainSpecif

현대 웹 개발에서는 프런트엔드와 백엔드의 분리가 매우 대중적인 추세가 되었으며, 이를 통해 개발자는 프로젝트를 더 잘 구성하고 프로젝트 개발 효율성을 향상시킬 수 있습니다. PHP와 Smarty는 프런트엔드와 백엔드 분리 개발을 달성하는 데 사용할 수 있는 매우 일반적으로 사용되는 두 가지 기술입니다. 이 기사에서는 PHP와 Smarty를 사용하여 프런트엔드와 백엔드 분리 개발을 수행하는 방법을 소개합니다. 프론트엔드와 백엔드 분리 개발이란 무엇입니까? 전통적인 웹 개발에서 프론트엔드는 주로 페이지 표시와 백엔드와의 상호 작용 논리를 담당합니다. 백엔드는 주로 비즈니스를 담당합니다.

PHP 개발자로서 템플릿 엔진을 사용하는 것은 자연스러운 선택입니다. Smarty는 HTML/CSS/JavaScript를 PHP 코드에서 분리하는 방법을 제공하여 개발자가 프로젝트를 더 잘 구성하고 관리할 수 있도록 하는 인기 있는 템플릿 엔진입니다. 이 기사에서는 PHP 개발 중에 Smarty 템플릿 엔진을 사용하는 방법을 알아봅니다. 1. Smarty 설치 먼저 Smarty를 설치해야 합니다. 이 기사에서는 Composer를 사용하여 설치하겠습니다.

PHP는 웹 애플리케이션을 개발하는 데 사용할 수 있는 강력한 서버측 스크립팅 언어입니다. 웹 개발 초기에 프로그래머들은 웹 애플리케이션을 개발하기 위해 HTML과 JavaScript 코드를 많이 사용했습니다. 그러나 이 접근 방식은 HTML 및 JavaScript 코드가 매우 복잡해지기 때문에 유지 관리가 어렵습니다. 이 문제를 해결하기 위해 Smarty 템플릿 엔진이 만들어졌습니다. Smarty는 W를 관리하고 생성하기 위해 PHP를 기반으로 개발된 템플릿 엔진입니다.

모듈로 등호 연산자(%)는 PHP에서 매우 일반적으로 사용되는 연산자이며 두 숫자를 나눈 나머지를 계산하는 데 사용됩니다. 이 기사에서는 모듈식 같음 연산자의 사용법을 더 자세히 살펴보고 독자의 이해를 돕기 위해 구체적인 코드 예제를 제공합니다. 먼저 간단한 예를 살펴보겠습니다. 한 숫자를 다른 숫자로 나눈 나머지를 계산해야 합니다. $a=10;$b=3;$remainder=$a%$b;echo"10 나누기 3 나머지 이다: &

SQL 연산자 사용: 1. 단일 열 일치, IN 연산자를 사용하여 열의 여러 값 일치. 2. 다중 열 일치, IN 연산자를 사용하여 여러 열의 값 일치; 3. 하위 쿼리, IN 연산자는 기본 쿼리 내에 중첩된 쿼리 문인 하위 쿼리와 함께 사용할 수도 있습니다.

인터넷의 급속한 발전과 업그레이드로 인해 웹 애플리케이션 개발에 널리 사용되는 프로그래밍 언어인 PHP는 점차 업계에서 매우 인기 있는 프로그래밍 언어가 되었습니다. 그러나 PHP 개발 과정에서 전통적인 코드 구현 방법은 코드 가독성과 유지 관리 용이성을 저하시키는 경우가 많습니다. 이때 효율적인 템플릿 엔진이 솔루션 중 하나가 됩니다. 많은 템플릿 엔진 중에서 Smarty는 강력한 기능과 우수한 성능으로 인해 PHP 개발자들 사이에서 인기 있는 선택이 되었습니다. 이 기사에서는 자세히 설명합니다.
