1. ホーム
  2. Web プログラミング
  3. ウェブ編集者

jsはリッチテキスト(正規表現)で最初の画像を取得します。

2022-01-18 05:37:32

 jsはリッチテキストで最初の画像を取得する url正規表現と文字列内のhtmlタグを削除
バックエンドは、0、1、2、3...の画像タグ (img) を含むリッチテキスト文字列を送信します。このタスクは、文字列内の最初の画像のURLを取得し、画像がない場合はnullを返すことです。

var imgUrlFun = function(str){
  var data = '';
   str.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/, function (match, capture) {
     data = capture;
   });
  return data
 }

文字列の中のhtmlタグの正規表現を削除する

var filterHTMLTag = function (str) {
  str = str.replace(/<\/? [^>]*>/g,''); // remove HTML tag
  str = str.replace(/[ | ]*\n/g,'\n'); //remove end-of-line whitespace
  str = str.replace(/ /ig,'');// remove 
  return str;
 }

js ueditorで最初の画像を取得する方法

ueditorで最初の画像をサムネイルとして取得したいのですが、どうすればよいですか?ueditorはすべてテキストとして保存します。

UE.getPlainTxt()は、段落書式付きのエディタ内のプレーンテキストコンテンツを取得します。
UE.getContentTxt()は、段落書式なしのプレーンテキストの内容をエディタに取得します。

ueditorは画像を直接取得する機能を提供していません。UE.getContent()ですべてのコンテンツを取得し、正規表現を使用して画像をフィルタリングします。Javaで書かれたフィルタメソッドを提供し、フォアグラウンドjsのコードは似ています。

Pattern p_img = Pattern.compile("(]+src\s*=\s*'\"['\"][^>]*>)");
Matcher m_img = p_img.matcher(content);
while (m_img.find()) {
String img = m_img.group(1); //m_img.group(1) to get the whole img tag m_img.group(2) to get the value of src
}

ueditor.all.min.jsを開くと、サポートされているすべてのメソッドが表示され、コメントも非常にわかりやすくなっています。

ueditor 公開記事の最初の画像をサムネイルとして取得するメソッド

画像のアドレスを正規にマッチングして、最初の画像のアドレスを取得する
これは、モジュール内またはグローバルCommonフォルダのfunctions.phpにある関数です。

/**
 * [getPic description]
 * Get the address of the first picture in the text
 * @param [type] $content [description]
 * @return [type] [description]
 */
 function getPic($content){
  if(preg_match_all("/(src)=([\"|']?) ([^ \"'>]+\. (gif|jpg|jpeg|bmp|png))\2/i", $content, $matches)) {
   $str=$matches[3][0];
  if (preg_match('/\/Uploads\/images/', $str)) {
   return $str1=substr($str,7);
  }
 }
}

使用方法デモ

$content=I('post.body');//Get rich text editor content
  $info=getPic($content);//use function to return matching address claim thumbnail if not empty
  if(! $info==null){
   $thumb=$info.'thumb240x160.png';
   $image = new \Think\Image();//Instantiate image processing, thumbnail function
   $image->open($info);// Generate a centered thumbnail cropped to 240*160
   $unlink=$image->thumb(240, 160,\Think\Image::IMAGE_THUMB_CENTER)->save($thumb);
  }else{
   $thumb='';
  }

js in dedecms は fckeditor で画像を取得します。

function get_firstimg(){
 //var c=document.getElementById('body').value;
 var c=FCKeditorAPI.GetInstance('body').GetXHTML(true);
 if(c){
 var fimg=c.match(/<img(. *?) src=["|'](. *?) ["|'](. *?) >/);
 if(fimg[2]){
 document.getElementById('picname').value=fimg[2];
 if(document.getElementById('ImgPr'))document.getElementById('ImgPr').src=fimg[2];//preview
 if(document.getElementById('picview'))document.getElementById('picview').src=fimg[2];//preview
 }
 }
}

コンプリートを1つ追加する

jsは、UEditorのテキストエディタで画像のアドレスを取得します。

書く前にWebで色々な方法を探したのですが、一番シンプルなアイデアは、1.UEditorでコンテンツを取得、2.取得した文字列をjqueryオブジェクトに変換、3.セレクタでimg要素を探し、src値を取得、というものでしょう。

var content= UE.getEditor('details').getContent();//Get the editor content
var $div = document.createElement("div");//create a div element object
$div.innerHTML = content;//fill the div with html
var $v = $($div);//convert from a dom object to a jquery object
$.each($v.find("img"),function (v,i) {//selector find img element, loop to get src value
console.log("src======"+i.src);
});

結果を印刷します。

上記のコードを書くまでに、いくつかの壁にぶつかり、回り道をしてしまいましたが、以下に私の開発プロセスのすべてを記します。

1. UEditorでコンテンツを取得する

これは簡単なステップで、エディターが提供するgetContent()関数を使用します。

2. 取得した文字列をjqueryオブジェクトに変換する

<p style="margin-top: 1em; margin-bottom: 1em; white-space: normal; box-sizing: border-box; padding: 0px; border: 0px; vertical-align: middle; line-height: 25px; list-style: none; color: rgb(58, 58, 58); font-family: 微软雅黑, 宋体, Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(247, 253, 255);">
	Summer is here and the constant heat is too much for even adults, let alone children. So should you give your child to wear socks again became the big thing on the mind of the baby mother, on the one hand, think you should give your child to wear, after all, this several reasons can not refuse.
	</p>
	<p style="margin-top: 1em; margin-bottom: 1em; white-space: normal; box-sizing: border-box; padding: 0px; border: 0px; vertical-align: middle; line-height: 25px; list-style: none; color: rgb(58, 58, 58); font-family: 微软雅黑, 宋体, Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(247, 253, 255); text-align: center;">
	<img alt="1.jpg" width="490" height="306" src="http://www.socksb2b.com/d/file/zixun/wazichangshi /2019-07-05/1b0038e6cf808ae9c091c34ded031de9.jpg" _src="http://www.socksb2b.com/d/file/zixun/wazichangshi/2019-07-05/ 1b0038e6cf808ae9c091c34ded031de9.jpg">
	</p>
	<p style="margin-top: 1em; margin-bottom: 1em; white-space: normal; box-sizing: border-box; padding: 0px; border: 0px; vertical-align: middle; line-height: 25px; list-style: none; color: rgb(58, 58, 58); font-family: 微软雅黑, 宋体, Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(247, 253, 255);">
	There is also a part of the baby mothers who have a different opinion and think it is better to not wear socks:.
	</p>
	<p style="margin-top: 1em; margin-bottom: 1em; white-space: normal; box-sizing: border-box; padding: 0px; border: 0px; vertical-align: middle; line-height: 25px; list-style: none; color: rgb(58, 58, 58); font-family: 微软雅黑, 宋体, Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(247, 253, 255);">
	1. small children often sweat, metabolism is relatively fast, socks if not breathable, there is a risk that the child will be crying because of raw foot sweat.
	</p>
	<p style="margin-top: 1em; margin-bottom: 1em; white-space: normal; box-sizing: border-box; padding: 0px; border: 0px; vertical-align: middle; line-height: 25px; list-style: none; color: rgb(58, 58, 58); font-family: 微软雅黑, 宋体, Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(247, 253, 255);">
	2. The soles of the feet have many acupuncture points, and without socks you can fully massage the soles of the feet. Beneficial to the operation of other body functions. Relieve constipation, indigestion and other symptoms.
	</p>
	<p style="margin-top: 1em; margin-bottom: 1em; white-space: normal; box-sizing: border-box; padding: 0px; border: 0px; vertical-align: middle; line-height: 25px; list-style: none; color: rgb(58, 58, 58); font-family: 微软雅黑, 宋体, Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(247, 253, 255);">
	It seems like both parents have a point, so should you wear socks or not?
	</p>


var content= UE.getEditor('details').getContent();

上記は私のエディタ内のコンテンツ(内容)ですが、一番簡単な方法は、このように

$(content)でjqueryオブジェクトに変換するのですが、$(content).html()では以下のように出力されます。

変換されたJqueryオブジェクトはコンテンツの最初のhtml要素pを表しており、残りのhtml要素は取得されないので、画像のアドレスを取得する3番目のステップができないことがわかります。
ここで追加できるのは、オンラインで利用できるメソッドの一つである

$(content).get(0).outerHTML は、以下のような結果を出力します。

get(1)、get(2)...は次のhtml要素のコードを順番に出力できる、ループして取得することを考え始めたが、元の場所に戻すのにループ回数が多く、全く取得できない、興味のある方は試してみてください。

jqueryのアイデアは壊れたので、ネイティブjsのアプローチを考え始め、ネットで見つけたのが、以下のサイトです。

var $div = document.createElement("div");//create a div element object
$div.innerHTML = content;//fill the div with html

というプリントアウトはとても良い。

曲がったところの最初の2行のコードで解決しました!ネイティブjsはすごいですね。
しかし、私はまだjqueryを使い慣れ、以下のセレクタとループを容易にするために、再びjqueryに変換しました。

var $v = $($div);//dom オブジェクトから jquery オブジェクトに変換する

3. セレクタはimg要素を見つけ、srcの値を取得します。

$.each($v.find("img"),function (v,i) {
console.log("src======"+i.src);
});

i.srcは画像のURLアドレスを直接取得することができます。

今回はリッチテキスト(正規表現)で1枚目の画像を取得するjsについて紹介しましたが、Webエディタで画像内容を取得する関連jsは、スクリプトのホームの過去記事または以下の関連記事を検索してください、今後ともスクリプトのホームをよろしくお願いします!(`・ω・´)