doutong6814 2014-10-08 13:29
浏览 22

使用PHP regex将CSS类添加到HTML标记

Can anyone suggest the best way to add a CSS class to an HTML element using PHP?

I need to modify a string which is the content of a WordPress post. If the post has a figure element at the start, I want to extract the element's opening <figure> tag and add the CSS class "big-image" to it before putting it back in place. The tag may or may not have a class attribute (with a value in single or double quotes), and it may have other attributes in various orders, so I can't just use preg_replace: I'll need to pull the tag out and run it through some logic with conditions to allow for these possibilities.

For example, I could have:

<figure id="foo" data-track="bar" class="fig">

or

<figure class='fig bah' id='foo' data-track='bar'>

or

<figure data-track="bar">

or just

<figure>

I only need to do this if the figure is the first thing in the content - if there's a figure anywhere else I'll ignore it. I've got as far as this first condition

if ( strpos( trim( $content ), '<figure' ) == 0 ) {

}

but I'm a bit baffled as to how to take it further. It seems to me I need a PHP function that'll use regex to find the first <figure> and split the $content string at the end of its opening tag, returning both halves. But there doesn't seem to be such a function - preg_split returns the string divided at the pattern, but not the pattern itself. I'd be grateful for any advice!

Edit = = = = = = = =

In answer to Amit's question here's an example of the desired input / output

<figure> to <figure class="big-image">

<figure class='boo'> to <figure class='big-image boo'>

<figure id="bar" class="boo"> to <figure id="bar" class="big-image boo">

  • 写回答

1条回答 默认 最新

  • dqh1992 2014-10-08 16:27
    关注

    I am not on system now so cannot write a code but just follow a simple procedure.

    1. get the post content in a variable using "the_content" or whatever you like.
    2. check if "<figure" come in the content.
    3. Read the string starting from "<figure" to first ">" char by char and save them in other variable lets say $remove_it .
    4. Now using $remove_it preg replace the post content.
    5. Resulting variable will return the required result.

    If you have any other query contact me directly on my new blog http://www.sourabhmodi.in/. I will be happy to help you out.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100