sql如何截取字符串中最后一次出现的字符后面的字符

admin
admin
admin
376
文章
102
评论
2022年3月12日08:00:50
评论
1,455

如果在wordpress的wp_posts表里面的post_content文章字段后面都有类似这样的一段代码,我们应该如果将里面的网址截取出来?换句话说,就是将截取wp_posts表的post_content字段特定的一个一串网址链接。

如果都是固定格式的话用sql来截取稍微简单点,但问题在于我们这里a标签里面的class和target属性的位置并不是固定的,可能会在href属性的前面。

<a rel="external nofollow" target="_blank" href="http://www.xxx.com/f/29610147-553171534-2f17c6" class="ztss-load" target="_blank" rel="noopener noreferrer">点击下载</a></p>

具体分如下几步来截取:

1、先选出http后面的字符

这里我们需要用到一个reverse倒序函数,就是将字符串的顺序反过来,因为上面的字符串是出现在post_content字段最后面,这段字符串前面还有很多内容,也会有http这个特征字符,按正常顺序可能没法定位,我们可以将字符串反过来,查找ptth这个特定字符:

select REVERSE(substr(REVERSE(post_content),1,instr(REVERSE(post_content),'ptth')+3)) from wp_content

代码解释:

-- 将post_content倒序,查找p在第几个字符,tth刚好三个字符,所以需要加3
  instr(REVERSE(post_content),'ptth')+3       

-- 从后往前截取post_content,字符数为instr(REVERSE(post_content),'ptth')+3
substr(REVERSE(post_content),1,instr(REVERSE(post_content),'ptth')+3)

-- 接着将选出来的数据再倒序一次,就是正常顺序了,将上一句sql整体写进函数reverse()
reverse(substr(REVERSE(post_content),1,instr(REVERSE(post_content),'ptth')+3)
)

接着将选出来的字符创建一个新表tmp

insert into tmp select 
REVERSE(substr(REVERSE(post_content),1,instr(REVERSE(post_content),'ptth')+3)) 
from wp_content

2、然后从tmp表中选出引号出现之前的字符

select substr(post_content,1,instr(post_content,'"')-1) from tmp

或者用left函数也可以搞定

left(post_content,instr(post_content,'"')-1)

另外,品自行这里还需要选出网址链接里面最后一个/斜杠后面的字符,可以执行下面的语句:

select REVERSE(substr(REVERSE(post_content_url),1,instr(REVERSE(post_content_url),'/')-1)) FROM tmp1

两个要求进行合并,创建新表tmp1 将获得的网址链接放在字段post_content_url里面,网址最后一个斜杠后面的字符放在font_name里面

insert into tmp1(post_content_url,font_name) select substr(post_content,1,instr(post_content,'"')-1),REVERSE(substr(REVERSE(substr(post_content,1,instr(post_content,'"')-1)),1,instr(REVERSE(substr(post_content,1,instr(post_content,'"')-1)),'/')-1)) FROM tmp
admin
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: